-2

Could you please kindly correct what I've done wrong?

var ipLocations = []; // variable in question

for (i = 0; i < ips.length; i++) {
    (function(i) {
        setTimeout(function() {

            $.getJSON(....

};

alert(ipLocations); // becoming '' here:(

Why ipLocations is '' here?

Jessica Ray
  • 65
  • 2
  • 5

1 Answers1

2

The code inside your for-loop is a non-blocking code... meaning your alert will fire way before your both getJSON and setTimeout callbacks populate ipLocations.

You can fix it by using Promises or a callback function for your getJSON function which would check if all the requests were finished, and if so, show the alert.

Shomz
  • 37,421
  • 4
  • 57
  • 85