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.
The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With