I'm trying to use jQuery to $().each
through inputs, make an AJAX call based on two of the inputs and update a third input. However, the AJAX call (Google Maps reverse geocoding) has a call limit, meaning I have to limit the number of requests I make per second.
I'm trying to throttle the each
by calling a setTimeout with a timeout that increases by 2 seconds for each iteration, but it just calls them all at once. Any insights on what I'm doing wrong? I'm basing my approach on this question but
a few things- specifically the fact that the elements affected change with each iteration- make this a bit more complicated.
<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>