setTimeout ( expression, timeout );
setTimeout() also returns a numeric timeout ID that can be used to track the timeout. This is most commonly used with the clearTimeout() method (see below).
Here’s a simple example:
<input type="button" name="clickMe" value="Click me and wait!" onclick="setTimeout('alert("'Surprise!"')', 5000)"/>
When a visitor clicks the button, the setTimeout() method is called, passing in the expression that we want to run after the time delay, and the value of the time delay itself - 5,000 milliseconds or 5 seconds.
It’s worth pointing out that setTimeout() doesn’t halt the execution of the script during the timeout period; it merely schedules the specified expression to be run at the specified time. After the call to setTimeout() the script continues normally, with the timer running in the background.
At the same time, this function also sets up a timed function using setTimeout() that sets the text colour back to black after 2 seconds:
Sometimes it’s useful to be able to cancel a timer before it goes off. The
clearTimeout()method lets us do exactly that. Its syntax is:
clearTimeout ( timeoutId );
timeoutId is the ID of the timeout as returned from the
For example, the following code sets up an alert box to appear after 3 seconds when a button is clicked, but the visitor can click the same button before the alert appears and cancel the timeout:
Try it out! Click the button below to start the timer, and click it again within 3 seconds to cancel it.
The important difference is that, whereas
expressionagain and again (unless you tell it to stop).
So when should you use it? Essentially, if you ever find yourself writing code like:
setTimeout ( "doSomething()", 5000 );
…then you should probably be using
setInterval ( "doSomething()", 5000 );
Why? Well, for one thing you don’t need to keep remembering to call
setTimeout()at the end of your timed function. Also, when using
setInterval()there’s virtually no delay between one triggering of the expression and the next. With
setTimeout(), there’s a relatively long delay while the expression is evaluated, the function called, and the new
setTimeout()being set up. So if you need regular, precise timing - or you need to do something at, well, set intervals -
setInterval()is your best bet.
As you’ve probably guessed, if you want to cancel a
setInterval()then you need to call
clearInterval(), passing in the interval ID returned by the call to
Here’s a simple example of
clearInterval()in action. When you press a button, the following code displays “Woo!” and “Yay!” randomly every second until you tell it to stop. (I said a simple example, not a useful one.) Notice how we’ve also used a
wooYay()function to make the “Woo!” or “Yay!” disappear after half a second:
And here it is in action. Click the button below to kick it off: