我正在做一个应用程序,我必须对每一个请求的几百个项目进行地理编码。所以我非常天真地做了一个循环调用google地图地理编码API。结果是,我的代码在很短的时间内对API进行了太多的调用,所以经过5-10次迭代之后,地理编码API就会有一个OVER_QUERY_LIMIT限制。在提到Google引用时,出现这种情况是因为:
该网页在太短的一段时间内超过了请求限制。
我的循环当前是这样的:
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);
}我如何实现一些类似睡眠()的函数,以随机延迟地理编码函数的调用,以避免API限制。我实现了一个愚蠢的时间循环,但它也使CPU哭泣。有什么想法吗?
发布于 2012-07-27 15:05:16
为什么不直接使用一个简单的setInterval,将其设置为每100 or或其他什么?
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现在您可以在任何时候:clearInvterval(setAPI);来阻止它运行。
它非常类似于使用setTimeout和调用Engineer所指出的函数。
发布于 2012-07-27 15:10:52
您可以实现这样的东西,而不是for循环:
(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);当然,如果由于'100'延迟而超出限制,您可以增加它。
https://stackoverflow.com/questions/11690470
复制相似问题