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);

All the major browsers support this: clearInterval can stop a timeout. Not so tidy after all, then..


One thought on “intervals and timeouts quirks

  1. 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! 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s