setTimeout Example 1
The setTimeout() function takes two parameters: 1) the function or code to call and 2) the number of milliseconds to wait before executing the code/function. A basic example below pops up an alert box 2 seconds after the button is clicked:
<input type="button" value="click me" onclick="setTimeout('window.alert(\'Hello!\')', 2000)" />
And here it is in action (if you're reading this post in a feed reader you may need to click through to the actual post to see this working):
setTimeout Example 2
The second example below does the same thing as the first, but calls a function instead when the button is clicked. The function initialises the timer which will call the show_alert function.
Note that the timeout is only triggered once, i.e. when timeout_trigger is called after 2 seconds it is not called again. To make it be continually called every two seconds you would need to add another call to setTimeout() at the end of the timeout_trigger function. This is covered in the final example of this post.
setTimeout and clearTimeout Example
setTimeout returns a value which stores a reference to the timer. The timer can then be cleared using the clearTimeout function. This is done in the following example:
When timeout_init() is called, the timeout reference is stored in the "timeout" variable. The name of the variable can be whatever you want, but it needs to be in the global scope, hence the "var timeout;" declaration at the start of the code.
Clicking the "test timeout" button starts the timer and the "clear timeout" button clears the timeout at the end. Here it is in action. Again, if you reading this post in a feed reader you may need to click through to the actual post to see this working.
Using setTimeout to make a countdown
The final example shows a countdown where the numbers count down from 10 to 0 updating every second. This is done by decrementing the counter number and then calling setTimeout again at the end of the timeout function call.
Here's the example code:
And here it is in action, again nothing that if you reading this in a feed reader you may need to click through to the actual post to see this working.