"Need help: Implementing a delay between each iteration of an AngularJS AJAX request loop. Suggestions

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,

Answer №1

If you're looking for an efficient way to handle asynchronous operations in JavaScript, utilizing promises and the $q service could be the perfect solution.

Let me illustrate how promises can be used in this scenario. By creating a delay service to manage the 10-second delay and a maps service for geocoding, both of which return promises, we can leverage $q.all() in the controller to ensure a precise timing between Google API calls.

angular.module( /* specify your module */ ).service('delay', ['$q', '$timeout', function ($q, $timeout) {
    return {
        start: function () {
            var deferred = $q.defer();
            $timeout(deferred.resolve, 10000);
            return deferred.promise;
        }
    };
}]);

angular.module( /* specify your module */ ).service('maps', ['$q', function ($q) {
    var geocoder = new google.maps.Geocoder();
    return {
        geocode: function (address) {
            var deferred = $q.defer();

            geocoder.geocode({
                'address': address
            }, function (results, status) {
                deferred.resolve(results);
                // Handle AJAX errors by rejecting the promise.
            });

            return deferred.promise;
        }
    };
}]);


angular.module( /* specify your module */ ).controller('geocodingController', ['delay', 'maps', '$q', function (delay, maps, $q) {
    var addresses = [/* List of addresses for geocoding */],
        addressIndex = 0,
        geocodeAddresses = function geocodeAddresses() {
            // Use $q.all to execute the callback after geocoding is complete and 10 seconds have elapsed.
            $q.all([delay.start(), maps.geocode(addresses[addressIndex])]).then(function (results) {
                addressIndex += 1;
                var geocodedData = results[1]; // Gained data from geocoding.

                // Process the results as needed.

                if (addressIndex < addresses.length) {
                    geocodeAddresses();
                }
            });
        };

    // Initiate the AJAX requests.
    geocodeAddresses();
}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clickable list element with a button on top

Within my web application, there is a list displaying options for the user. Each 'li' element within this list is clickable, allowing the user to navigate to their selected option. Additionally, every 'li' element contains two buttons - ...

jQuery button click event not registering

Confused by what should be a simple solution, I find myself struggling to figure it out at the moment. All I have is this button: <button id="logout" type="button">Logout</button> It's meant to trigger this jQuery code enclosed in script ...

Storing data downloaded through Angular in a factory for safekeeping

I've been diving into Angular for a while now. I have a database with multiple tables, including a clients table and several others containing client-related data. The data in these tables isn't too large. To minimize http calls, my idea was to l ...

Display or hide a div element when hovering over it, while also being able to select the text within

I am trying to display and conceal a tooltip when hovering over an anchor. However, I want the tooltip to remain visible as long as my cursor is on it. Here is the fiddle link $('#showReasonTip').mouseover(function(){ $(this).parent().find(&apo ...

"Utilizing AngularJS for advanced filtering and searching functions, along with

After exploring various solutions on Stack Overflow to identify unique values in angular.js (I am still learning), I am faced with a challenge. My goal is to present these unique values within a select form and use them as filters for data displayed in a t ...

The failure of the $getJSON function to execute properly

Having trouble with handling errors in the $getJSON .fail method: this.flickrPics = ko.observableArray(); ko.computed(function() { $.getJSON( 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?', { ...

Is your blockui overlay failing to cover the entire page?

I have implemented blockui to display a "Wait ... loading" popup on my webpage. It is mostly working fine, but I am facing a small issue where the overlay does not cover the entire width of the scroll window when I scroll right (although it covers the full ...

Tips for reformatting table row data into multiple rows for mobile screens using ng-repeat in Angular

Just started using Angular JS and I have some data available: var aUsers=[{'name':'sachin','runs':20000},{'name':'dravid','runs':15000},{'name':'ganguly','runs':1800 ...

Eliminating an element from an array without the need for iteration

I've been reviewing some documentation, but I have a hunch that there may be a simpler way to eliminate one element from an array without having to utilize an iteration loop. http://jsfiddle.net/G97bt/1/ Check out the updated jsFiddle example: http: ...

Please replicate an element based on user input using Javascript

When I click on the ADD button, the text appears below but in the same column. There are 2 input fields. I have used: <input id="accordion_input" type="text"/> Another one is: <div id="accordion_body" class="panel-body"></div&g ...

How can we use AJAX to incorporate a "like" feature?

I have nearly completed my website, but there is one final obstacle. I would like to add an ajax liking feature. The idea is that when a user clicks on the button, an ajax call should be triggered to increase the value in the database and update it on the ...

Steps for Removing Multiple CSS Styles from an Element's Style:

When my application generates inline styles, I sometimes need to remove the height, width, and max-width styles from certain elements. I have identified the element using this code: const elems = window.$('.myElements'); window.$.each(elems ...

Exploring the integration of Mariadb COLUMN_JSON data in JavaScript

I am encountering difficulties while attempting to access COLUMN_JSON data in JavaScript. I referred to a MariaDB JSON example and inserted it into a table with the following query: UPDATE myTable SET myJsonColumn = COLUMN_CREATE('color', ' ...

The procedure of Change Detection and the specific moment when OnPush properties are verified

According to a source, Angular performs 14 operations when checking for changes. But at what specific moment does it verify if the component has ChecksEnabled set to false (OnPush), and especially, when does it check if any @Input properties have changed i ...

Guide to generating an iframe that is triggered by a button click with the help of jquery

Is it possible to dynamically insert an iframe into a column div on a web page by clicking on it? I want the iframe to remain hidden when just viewing the page, but to become visible when a button is clicked. How can this be achieved? ...

What is the correct placement for the return next() statement within the Restify module in Node.js?

Consider the following code snippet that queries a user from a database and then checks for their phone number: module.exports = function (username, req, res, next) { var query = User.where('username', new RegExp('^' + username + ...

The startOf function in moment.js is functioning properly, however the endOf function is returning an

Hey there, I was attempting to retrieve the start and end date of a specified month using Moment.js. Here is the code snippet I used: //function to get the ranges of month specified function Calculate() { // get entered month const month = docum ...

Collaborating on JavaScript files across different projects

My framework project contains validation JavaScript that I want to incorporate into my regular website. Within the framework folder, I define core functionality and validation using attributes. The issue arises because the framework project also includes ...

The Less compiler (lessc) encounters an issue on a fresh operating system. ([TypeError: undefined is not a function])

After setting up my new development environment on Windows 10, I encountered an issue with less. Following the instructions on lesscss.org, I installed less using: npm install -g less The installation process completed without any errors. However, when ...

Stop users from navigating back to index.html page on Cordova PhoneGap

I'm currently working on a web application that I access through the PhoneGap AppBrowser for mobile devices. The challenge I'm facing is with the index.html page, which I use as a splash screen but later want to prevent users from revisiting afte ...