2014-10-09 42 views
-3

我正在使用Google的Geocoder API,并使用下面的循环来达到速率限制。减缓这种情况的最佳方法是什么?数组长度各不相同,但不超过50个项目。控制循环速度的最佳方法是什么?

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); 
    } 
    }); 
} 
+1

['setInterval'(https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval)在谷歌地图API V3的[OVER_QUERY_LIMIT – Pointy 2014-10-09 00:31:44

+0

可能重复:如何在Javascript中暂停/延迟以减慢速度?](http://stackoverflow.com/questions/11792916/over-query-limit-in-google-maps-api-v3-how-do-i-暂停延迟在JavaScript的到sl) – geocodezip 2014-10-09 00:40:07

+0

@Pointy - 谢谢。我想过,但不确定这是否合适。 – 2014-10-09 00:48:21

回答

1

把所有的代码,你的循环称为mySuperCoolLoopFunction函数内内则使用此代码来调用该函数在指定的时间间隔:

var numberOfMilliseconds = 1000 
setInterval(mySuperCoolLoopFunction, numberOfMilliseconds) 

您可以阅读所有关于JavaScript的setInterval函数here为尖指出。第一个参数是一个函数,第二个参数是在再次调用函数之前要等待的毫秒数。

您可以将setInterval调用的结果分配给一个变量,并允许您在某个点停止时间间隔。就像这样:

myInterval = setInterval(coolFunction, 1000) 
... 
clearInterval(myInterval) 
相关问题