7

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.

xsl
  • 16,188
  • 16
  • 69
  • 111

1 Answers1

10

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.

user113716
  • 299,514
  • 60
  • 431
  • 433
  • You're right. I'm using AJAX request. I will update the question. – xsl Sep 06 '11 at 03:18
  • 1
    It's not *that* different - have your AJAX callback do the call to setTimeout (presuming your .ajax function has callback functionality when it sucessfully completes). What do you plan to do if the AJAX call doesn't complete sucessfully? – RobG Sep 06 '11 at 03:28
  • I would ignore unsuccessful calls. I actually have multiple AJAX calls within the function, so I can't really do a setTimeout if one completes successfully. – xsl Sep 06 '11 at 03:32
  • 1
    @xsl: Increment a counter for each request that is sent. Then decrement the counter in the callbacks (whether successful or not). When the counter reaches zero, have the callback that decremented to zero invoke the recursive invocation. – user113716 Sep 06 '11 at 03:35
  • 1
    For future readers: you want setTimeout, not setInterval. If your remote call takes longer than your setInterval value it will wind up getting fired more than once. – Kent Brewster Sep 06 '11 at 04:29
  • Solved it, but made one big ajax request instead of many small ones. It was simply getting to complicated the other way. – xsl Sep 06 '11 at 05:04