intervals and timeouts quirks
Monday, 3. October 2005, 22:41:38
JavaScript has four methods for controlling timer events: setInterval(), setTimeout(), clearInterval(), clearTimeout(). They are pretty self-explanatory and simple to use:
var someTimeout = setTimeout(myFunction, 500); // I want something to happen in half a second
The interval functions work the same way. The only gotcha is that calling setTimeout or setInterval more than once assigning to the same variable will create multiple timeouts because the variable only stores a reference and isn't the timeout itself:
clearTimeout(someTimeout); // oops, changed my mind. don't want that anyway
var someTimeout = setTimeout(myFunction, 500); // Setting intial timeout
It all makes sense, no? Until you meet the following script:
someTimeout = setTimeout(myFunction, 500); // overwriting variable means we can no longer cancel first timeout
clearTimeout(someTimeout); // so this only cancels the second one
var someTimeout = setTimeout(myFunction, 500);
clearInterval(someTimeout);
All the major browsers support this: clearInterval can stop a timeout. Not so tidy after all, then..
Either clearX function clears any setX timer. At least it's consistent!
By Andrew Gregory, # 4. October 2005, 04:22:53