leonsas
leonsas

Reputation: 4908

Delaying javascript to avoid API limits

I'm doing an app where I have to do geocode a few hundred of items per request. So very naively I just did a for-loop calling the google maps geocoding API. What happens is that my code does too many calls to the API in very short time, so after 5-10 iterations the geocoding API just answers with an OVER_QUERY_LIMIT limit. Referring to the Google API reference, this happens because:

The webpage has gone over the requests limit in too short a period of time.

My loop currently is something like this:

for (var i = 0; i < dict.nodes.length; i++) {
    (function (i) {
        g.geocode({'address': dict.nodes[i].location}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                dict.nodes[i]["geocoded_location"] = results
            }
        })
    })(i);
}

How can I implement something like a sleep() function to randomly delay the call of the geocoding function to avoid the API limit. I implemented a dumb while-loop but it also makes the CPU cry. Any ideas?

Upvotes: 1

Views: 1030

Answers (2)

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67011

Why not just use a simple setInterval, set it to every 100ms or something?

var i = 0;

var setAPI = setInterval( function () { 

    if ( i < dict.nodes.length ) {
        g.geocode({'address': dict.nodes[i].location}, function (results, status) {
             if (status == google.maps.GeocoderStatus.OK) {
                dict.nodes[i]["geocoded_location"] = results
             }
        });
    }

    i++;

  }, 
100); //100ms delay

Now you can at any point: clearInvterval(setAPI); to stop it from running.

It's very similar to using setTimeout and calling a function as Engineer pointed out.

Upvotes: 4

Engineer
Engineer

Reputation: 48793

You can implement something like this,instead of for loop:

(function nextCall(i){
    if(i < dict.nodes.length){
        g.geocode({'address': dict.nodes[i].location}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                dict.nodes[i]["geocoded_location"] = results;
            }
        });
        setTimeout(function(){   nextCall(i+1)   },100);
    }
})(0);

Of course,if it will be exceeded the limit by '100' delay, you can increase it.

Upvotes: 2

Related Questions