chrsmrrtt
chrsmrrtt

Reputation: 197

getJSON requests looping through an array of parameters with delay between each call

Can anyone help me understand why the following jQuery/Javascript code, rather than running at a rhythmic 1-per-second-ish beat rate, instead has this cascading avalanche of ajax calls (slow to many-per-second)?

var i = 0, l = data.length;

function geocode() {

$.getJSON(
    'https://maps.googleapis.com/maps/api/geocode/json',
    {
        key: "xxxxx",
        sensor: false,
        address: data[i][3],
        region: 'gb'
    },
    function(d, textStatus, jqXHR) {
        if(d["status"] == "OK") {
            console.log(data[i][3]);
            console.log(d["results"][0]["geometry"]["location"]);
            i++;
            if(i < l) { window.setInterval(geocode, 1000); }
        }
    }
);

}

geocode();

In my head this flows thus:

  1. Call geocode the first time
  2. Ajax request is made
  3. On success (which is an arbitrary amount of time later) I read the results
  4. Increment the index
  5. If we've not yet expended the array, set up another call to geocode to start in 1 second

For reference: "data" is a nested array of UK postcodes which I'm trying to retrieve coordinates for using Google's geocoding API.

Upvotes: 1

Views: 288

Answers (1)

acarlon
acarlon

Reputation: 17282

You keep setting a new interval and never cancel the previous one. You should either cancel the interval using clearInterval() or use a one off setTimeout.

If you use an interval then when you set the interval save the value:

var intervalId;
....
intervalId = setInterval(...);

then

clearInterval(intervalId); 

when you need a new interval. OR use setTimeout() and reissue as required.

Upvotes: 3

Related Questions