Skip navigation.

exploreopera

| Help

Sign up | Help

intervals and timeouts quirks

,

Today I came across an oddity I wasn't aware of or had forgotten. It is the sort of quirk that makes you remember what a messy language JavaScript is: you can use clearInterval() to stop a timeout!

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
clearTimeout(someTimeout); // oops, changed my mind. don't want that anyway
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: var someTimeout = setTimeout(myFunction, 500); // Setting intial timeout
someTimeout = setTimeout(myFunction, 500); // overwriting variable means we can no longer cancel first timeout
clearTimeout(someTimeout); // so this only cancels the second one
It all makes sense, no? Until you meet the following script: var someTimeout = setTimeout(myFunction, 500); clearInterval(someTimeout); All the major browsers support this: clearInterval can stop a timeout. Not so tidy after all, then..

"Tested only in FireFox" signature errorGMail loading problems

Comments

avatar
Just for some completeness, a quick test shows clearTimeout clears intervals. Checked in Opera, Firefox and IE6.

Either clearX function clears any setX timer. At least it's consistent! :smile:

By Andrew Gregory, # 4. October 2005, 04:22:53

Write a comment

You must be logged in to write a comment. if you're not a registered member, please sign up.