Executing Recursive Functions in AngularJS with a Delay - A Step-by-Step Guide

Here is a function that I have:

$scope.getContactsByScroll = function() {
  $scope.pageN = $scope.pageN + 1;
  if (!$scope.allDataIsLoaded){
    fetchMyDataService.getContactsByScrollService($scope.pageN).then(function(response) {
      if (response.length === 0){
        $scope.allDataIsLoaded = true;
      }
      else if (response.length !== 0 && !$scope.allDataIsLoaded){
        angular.forEach(response, function(el) {
          $scope.contacts.push(el);
        });
        //$timeout(function() {
          $scope.getContactsByScroll();
        //}, 2000);
      }
    }).catch(function() {
      $scope.allDataIsLoaded = true;
    });
  }
};

However, it calls itself multiple times even when $scope.allDataIsLoaded is set to false.

Setting a timeout seems to resolve the issue temporarily. Is there a way to delay the function without relying on a timeout?

Answer №1

Avoid using timeouts in asynchronous functions:

  1. Exceeding the timeout may result in unnecessary requests.

  2. A timeout longer than the request time can cause unnecessary delays.

Instead of timeouts, consider using a promise chain for recursive requests. You can try implementing something similar to this:

var asyncService = function ($timeout)
    {
        var someData = 10;
        var service =
            {
                FetchData: function (someArray)
                {
                    someData++;
                    //The timeout here is only for demonstration purposes
                    return $timeout(function () { return someData }, 1000)
                        .then(function (result)
                        {
                            return service.ProcessData(result, someArray);
                        });
                },
                ProcessData: function (data, someArray)
                {
                    console.log(data);
                    if (data == 15)
                    {
                        return someArray;
                    }
                    else
                    {
                        someArray.push(data)
                        return service.FetchData(someArray);
                    }
                }
            };
        return service;
    }

Check out this plunker link for a demonstration.

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

Changing the background color of the canvas using Javascript

I want to create a rect on a canvas with a slightly transparent background, but I don't want the drawn rect to have any background. Here is an example of what I'm looking for: https://i.stack.imgur.com/axtcE.png The code I am using is as follo ...

Deciphering basic XML with Javascript/Ajax

I am trying to update the content on a page dynamically based on an XML Ajax response. To test this functionality, I have created a static PHP-generated XML file with just one tag. If the tag contains the text "yes", it should show "AVAIL"; otherwise, it s ...

Redirecting with VueJS Router to a specific path on the server

I have set up my router with the following configurations: export default new Router({ mode: 'hash', linkActiveClass: 'open active', scrollBehavior: () => ({ y: 0 }), routes: [ { path: '/', .... In ...

"What is the best way to retrieve the value of an HTML input in

I am looking to store a variable that can be retrieved from JavaScript and then utilized in PHP upon form submission. For this purpose, I have added an input field in the HTML code: HTML <input type="hidden" name="videoname_var" id="videoname_var" me ...

Dealing with spaces in Discord.js arguments can be tricky, but with the right

I'm currently working on enhancing my Discord bot to handle commands with argument spaces. Within my index.js file, I've defined the args variable in the following way: const args = message.content.slice(prefix.length).split(/ +/); const commandN ...

JavaScript code that retrieves the current exchange rate of Bitcoin (BTC)

Seeking to create a JavaScript function that returns the current exchange rate for BTC/USD. Keeping it simple without using server-side calculations, just a user-friendly feature. I have 2 text fields and want one value to update automatically when the oth ...

Issue with ng-show not toggling visibility on ng-click event in AngularJS

When I click on an Edit Mode link, I want to display some Edit icons. I've tried using ng-click with ng-class and ng-show but it's not working as expected. Here is the HTML code: <div click-to-edit="questions.n1.name" class="row question"> ...

Having trouble getting the mock module to work with mockImplementation

I have been facing a challenge in properly testing this File. Some tests require mocking the entire module, while others only need specific methods mocked. I have tried various combinations, but currently, for one specific test below, I am attempting the f ...

Youtube video embedding showing cut edges on smaller screens

Looking for assistance with a Next.js and tailwind site I am building. Having trouble getting the video component to display properly on mobile screens. Tried various fixes but the video still gets cut off on smaller screen sizes. If anyone has a soluti ...

What is the best way to handle dynamic URLs in Protractor testing?

We have decided to utilize AngularJS for the development of our website, which results in dynamic URL changes. As a result, I find myself needing to adjust the URLs each time they change. How can I successfully verify these dynamic alterations using Prot ...

Utilize an enum from a shared library by exporting it and incorporating it into a TypeScript project

Currently, I am in the process of developing a library where a React component is being exported along with some interfaces and an enum. After compiling the typescript project, I realized that the library is specifically for React and not typescript, so I ...

Creating a function that uses setInterval to continuously update the input with a specific value

I am looking to use the setInterval function to continuously update the value of #test1. Additionally, I want the value of #test1 to be cleared and reset to 1 second after the user clicks a button. Example output can be found here: http://jsfiddle.net/eK ...

Have you ever found yourself in a situation where you must include 'javascript:' in an onclick event?

It's important to note that the protocol is not necessary in an onclick event: onclick="javascript:myFunction()" Avoid onclick="myFunction()" Recommended I recently came across an interesting article on Google Analytics which highlighted their use ...

Ways to terminate session using ajax when input is empty; Notice of an undefined variable

Warning: Variable 'outputname' is undefined There is a query in the file memberSearch.php. I want to echo the $outputname variable in another PHP file inside an input tag. However, when I try to echo ($outputname) in another file, it returns an ...

Completing a submission on a bootstrap form, using innerHTML and displaying an alert

I am currently having an issue with navigating to the home page after submitting a form in Bootstrap. Although I have successfully implemented an alert message upon submission, the page does not redirect to the home page as expected. Instead, it redirects ...

Error Encountered in MERN Stack Development: TypeError Thrown Due to Inability to Convert Undefined

Currently, I am following the MERN Stack, Front To Back Course by Traversy Media. I am in the process of setting up the login functionality for the application. Despite ensuring that my code matches his exactly, I am encountering an error: TypeError: Canno ...

The filterSelectedOptions feature in Material UI Lab's autocomplete does not seem to be functioning properly when used in conjunction

When using autocomplete to select dates, I am encountering an issue where the selected options are not being filtered. This allows me to select multiple instances of the same data. Removing the OnChange prop resolves this issue, however, it prevents me f ...

"Encountering an error retrieving weather forecast API in JavaScript - issue with

I've been attempting to fetch the weather forecast API JSON in a similar manner to how I accessed the current weather API, but unfortunately, it doesn't seem to be working no matter what approach I take. let inOneDay = { fetchWeather: functio ...

Setting up Requirejs in a separate file

My current setup involves using requirejs in my main.js file. Here is a snippet of the content: requirejs.config({ async: true, parseOnLoad: true, packages: [], paths: { jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1. ...

Adding a button input and deleting non-functional parent elements

Here is a simple append function using jQuery, and it's working perfectly. However, the issue arises when I try to append a button and remove the parent tr upon clicking. The problem lies in using remove parent, as it doesn't seem to work as exp ...