JavaScript setTimeout Function - JavaScript Timing Events
November 16, 2007 by Blogging Developer
JavaScript features a couple of methods that lets you run a piece of JavaScript code (javascript function) at some point in the future. These methods are:
* setTimeout()
* setInterval()
In this tutorial, I'll explain how setTimetout() method works, and give a real world example. You may find the details of setInterval() method in JavaScript setInterval Function - JavaScript Timing Events
setTimeout()
window.setTimeout() method allows you to specify a piece of JavaScript code (expression) will be run after specified number of miliseconds from when the setTimeout() method is called.
Syntax
var t = setTimeout ( expression, timeout );
The setTimeout() method returns a numeric timeout ID which can be used to refer the timeout to use with clearTimeout method. The first parameter (expression) of setTimeout() is a string containing a javascript statement. The statement could be a call to a JavaScript function like "delayedAlert();" or a statement like "alert('This alert is delayed.');". The second parameter (timeout), indicates the number of miliseconds to pass before executing the expression.
Example
An alert box will be shown 5 seconds later when you clicked the button.
clearTimeout()
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 );
where timeoutId is the ID of the timeout as returned from the setTimeout() method call.