-1

I am making geocoding requests from client-side for an array of 25 addresses and received this error for 14 of them. Here's my code, with what I thought would be enough of a delay:

$(function() {

    var addresses = ["... bunch of addresses..."];

    var geocoder = new google.maps.Geocoder();
    var outputContainer = $('#resultsContainer');

    addresses.forEach(function(address) {
        setTimeout(function() {
            geocoder.geocode({
                'address': address
            }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    outputContainer.append('<p>' + address + ' : ' + results[0].geometry.location.A + ' , ' + results[0].geometry.location.k + '</p>');
                } else {
                    outputContainer.append('<p>' + address + ' : Not found, Status: ' + status.toString() + '</p>');
                }
            });
        }, 4000);
    });
})

I'm very likely missing something here, but can't for the life of me think of what at the moment. Any suggestions?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
codedog
  • 2,488
  • 9
  • 38
  • 67

1 Answers1

1

Setting a timeout inside your loop for each index doesn't do a whole lot when you set the same timeout for each index. The looping will complete quickly (milliseconds I'd guess) and the AJAX requests will still all fire at the same time. Google only allows one request a second (or something like that, I am not aware of the exact rate they allow).

If you multiply a smaller timeout by the current index in the loop then you can stagger the requests. I'd start low and see what you can get away with if this is something the user will be waiting for.

Here's a quick example of what I mean:

addresses.forEach(function(address, index) {
    setTimeout(function() {
        //some really fun stuff happens here
    }, 500 * index);
});

This will run the "really fun stuff" one at a time, once every half second. The first index (0) will be given no timeout duration, the second will get 500ms, the third 1s, so on and so forth.

Jasper
  • 75,717
  • 14
  • 151
  • 146
  • Brilliant! Incremental factor of 500 ms was not enough it seemed. The last few still triggered the error. I pushed it to 1000 and voila! There's no UI involved here so time is not critical. – codedog Apr 09 '14 at 22:51