I am trying to run a loop that makes 20-200 ajax requests, but I need to add a 10-second delay between each call in order not to overwhelm the google.maps.Geocoder
. Since ajax requests are asynchronous, I want to call the next request only after the response from the previous one has succeeded. If the response comes too quickly, I still want the delay to happen.
This is the code that I have come up with so far:
...
$scope.addressList = ....;
$scope.taskCount = $scope.addressList.length;
geoTaskLoopAsync();
function geoTaskLoopAsync(){
// decrease taskCount on success
var geo = new google.maps.Geocoder();
geocoder.geocode( {
'address': address
}, function(results, status) {
$scope.$apply( function () {
// do something with response
if($scope.taskCurr <= $scope.taskCount){
$scope.taskCurr++;
return geoTaskLoopAsync();
}
return;
});
});
What should I do next?
Would it work if I added this:
stop = $timeout(function() {
if($scope.taskCurr <= $scope.taskCount){
geoTaskLoopAsync();
} else {
$timeout.cancel(stop);
}
}, 10000);
Or is there another way to approach this?
Thank you,