-3

I'm using Google's Geocoder api and I'm hitting the rate limits using the loop below. What's the best approach to slow this down? The results array length varies, but doesn't exceed 50 items.

for (var key in data) {
var results = data[key];
var address = results['Address'];

//test
if (geocoder) {
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
      map.setCenter(results[0].geometry.location);

        var infowindow = new google.maps.InfoWindow(
            { content: '<b>'+address+'</b>',
              size: new google.maps.Size(150,50)
            });

        var marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map, 
            title:address
        }); 
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
        });

      } else {
        alert("No results found");
      }
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}
Paul Dessert
  • 6,363
  • 8
  • 47
  • 74
  • 1
    [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval) – Pointy Oct 09 '14 at 00:31
  • possible duplicate of [OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?](http://stackoverflow.com/questions/11792916/over-query-limit-in-google-maps-api-v3-how-do-i-pause-delay-in-javascript-to-sl) – geocodezip Oct 09 '14 at 00:40
  • @Pointy - Thanks. I thought about that, but wasn't sure if it was appropriate for this. – Paul Dessert Oct 09 '14 at 00:48
  • Whoever downvoted, please tell me why. I'm happy to improve the question if needed. – Paul Dessert Oct 09 '14 at 00:49

1 Answers1

1

Put all the code within your loop inside a function called mySuperCoolLoopFunction then use this code to call that function at a specified interval:

var numberOfMilliseconds = 1000
setInterval(mySuperCoolLoopFunction, numberOfMilliseconds)

You can read all about Javascript's setInterval function here as Pointy pointed out. The first argument is a function, and the second argument is the number of milliseconds to wait before calling the function again.

You can assign the result of the setInterval call to a variable and that will allow you to stop the interval at some point. Like this:

myInterval = setInterval(coolFunction, 1000)
...
clearInterval(myInterval)
Nathan Manousos
  • 13,328
  • 2
  • 27
  • 37