我正在尝试通过输入使用 jQuery 来 $().each
,基于两个输入进行 AJAX 调用并更新第三个输入。但是,AJAX 调用(谷歌地图反向地理编码)有调用限制,这意味着我必须限制每秒发出的请求数。
我试图通过调用 setTimeout 来限制 each
,每次迭代的超时增加 2 秒,但它只是一次调用它们。关于我做错了什么的任何见解?我的方法基于 this question但
一些事情 - 特别是受影响的元素随着每次迭代而变化 - 使这有点复杂。
<button class="identify-locations">Identify locations</button>
<div class="row">
<input class="address"></input>
<input class="lat"></input>
<input class="lng"></input>
</div>
<!-- the same thing over again 30 times -->
<script>
$(".identify-locations").click(function(event){
var time = 2000;
$(".row").each(function(){
if($(this).find(".lat").val() == '' && $(this).find(".lng").val() == ''){
setTimeout( geocodeLocation($(this)), time);
time += 2000;
}
});
});
function geocodeLocation(object, time){
address = object.find(".address").val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address},
function(results_array, status) {
if(status == 'OK'){
object.find(".lat").val( parseFloat(results_array[0].geometry.location.lat()) );
object.find(".lng").val( parseFloat(results_array[0].geometry.location.lng()) );
updateCount();
}
});
}
</script>
最佳答案
您正在使用一个立即返回结果的函数调用 setTimeout。
改为做
if($(this).find(".lat").val() == '' && $(this).find(".lng").val() == ''){
var $current = $(this);
setTimeout(function() { geocodeLocation($current)}, time);
time += 2000;
}
另请查看 Passing parameters into a closure for setTimeout
请注意有用的 .bind 在 IE8/Safari5 中不可用
关于javascript - 一种更优雅的节流 jQuery $().each 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30795440/