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.
Make a function that recursively invokes itself at the end on a timer:
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 anifstatement to make the recursion dependent on some criteria: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.