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
2010-09-28 16:48:27
Yes, but **don't** use a string, use the actual function reference.
T.J. Crowder
2010-09-28 16:51:31
+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
2010-09-28 16:49:01
+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
2010-09-28 16:49:09
This would result in it running one last time before stopping, the check needs to be at the beginning of the function.
Nick Craver
2010-09-28 16:51:37
Yes. Depending on where the break condition is calculated, this might bewhat you want.
kevingessner
2010-09-28 16:56:10