views:

28

answers:

3

How do I set up a setInterval render loop that breaks, once a condition is met?

A: 

If you ask on how to stop a function call that has been set using setInterval(), just use the clearInteval() function. You first have to save a reference to the setInterval function and than use this reference to stop the interval:

var int=self.setInterval("your_function_name()",1000);
if(condition){
    clearInterval(int)
}
Kau-Boy
Yes, but **don't** use a string, use the actual function reference.
T.J. Crowder
+4  A: 

You can store the interval ID and clear it via clearInterval(), for example

var timer = setInterval(myFunction, 1000);

function myFunction() {
  if(condition) {
    clearInterval(timer);
    return;
  }
  //do stuff
}

Or if you can just call clearInterval() where setting the condition, so the next interval doesn't run, having no logic for this in the function itself.

Nick Craver
+3  A: 

clearInterval stops the repetition from setInterval, using the ID returned by setInterval:

var interval = setInterval(function() {
    // do your loop
    if (loop_should_stop) {
        clearInterval(interval);
    }
}, dt);
kevingessner
This would result in it running one last time before stopping, the check needs to be at the beginning of the function.
Nick Craver
Yes. Depending on where the break condition is calculated, this might bewhat you want.
kevingessner