Reputation: 197
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:
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
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