Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an asynchronous function every N seconds in JavaScript [duplicate]

I have a Java Script function that takes an undefined time to finish. In a loop I want to wait until the function is finished, then wait a defined time (e.g. 5000 ms) and call the function again. How do I accomplish this in Java Script?

Basically I want this:

call function and wait until it is finished
wait another 5000 seconds
call function and wait until it is finished
wait another 5000 seconds
...

The function itself looks like this:

for every group in list

    .ajax(delete group items; get group items; add group items)

The problem I currently have is that in the middle of the loop the function is somehow called again.

like image 773
xsl Avatar asked Sep 06 '11 02:09

xsl


People also ask

How do you call a function repeatedly every 5 seconds in JavaScript?

The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function.

How do you call a function after every second?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.

Are JavaScript function calls asynchronous?

Synchronous vs AsynchronousBy default, JavaScript is a synchronous, single threaded programming language. This means that instructions can only run one after another, and not in parallel. Consider the little code snippet below: let a = 1; let b = 2; let sum = a + b; console.


1 Answers

Make a function that recursively invokes itself at the end on a timer:

(function my_func() {
    // your code
    setTimeout( my_func, 5000 );
})();

This immediately invokes my_func, and then recursively invokes it at the end of the function after a 5 second delay.

This way the timer doesn't begin until your code is complete.


You could place the setTimeout() in an if statement to make the recursion dependent on some criteria:

(function my_func() {
    // your code
    if( some_criteria_is_met ) {
        setTimeout( my_func, 5000 );
    }
})();

Note that this implies that your code is synchronous. If you're running some asynchronous code, like an AJAX request, the approach will be a little different.

like image 84
user113716 Avatar answered Oct 12 '22 13:10

user113716