我正在尝试使用jQuery通过
我试图通过使用setTimeout来限制
$().each
输入,基于其中两个输入进行AJAX调用,并更新第三个输入。然而,AJAX调用(Google Maps反向地理编码)具有调用限制,意味着我必须每秒限制请求的数量。我试图通过使用setTimeout来限制
each
的速度,每次迭代的超时时间增加2秒,但它只是一次性调用了所有函数。您认为我做错了什么吗?我的方法基于这个问题,但有些事情(特别是每次迭代中受影响的元素会改变)使得这个问题更加复杂。<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>