The window object allows execution of code at specified time intervals. setTimeout()
and setInterval()
allow for scheduling the execution of a piece of code.
Method | Description |
setTimeout(function, milliseconds) | executes the given code once after a specified number of milliseconds. |
setInterval(function, milliseconds) | executes it repeatedly after a specified number of milliseconds has passed. |
window.setTimeOut()
window.setTimeout()
method can be written without the window prefix.
window.setTimeout(function, milliseconds);
The first parameter is a function to be executed. The second parameter indicates the number of milliseconds before execution.
An example to show an alert after 2 seconds (2000 milliseconds):
function boo(){alert('Boo!');} setTimeout(boo, 2000); //4
As you can see the function returned the integer 4, this is the ID of the timeout. You can use this ID to cancel the timeout using clearTimeout().
In the following example, if you're quick enough, and clear the timeout before two seconds have passed, the alert will never be shown.
var id = setTimeout(boo, 2000); clearTimeout(id);
function boo() {console.log('boo')};
window.setInterval()
window.setInterval()
method can be written without the window prefix.
window.setInterval(function, milliseconds);
The first parameter is the function to be executed. The second parameter indicates the length of the time-interval between each execution.
Using setInterval()
you can schedule boo() to execute every two seconds.
function boo(){console.log('boo');} var id = setInterval(boo, 2000);
You can cancel the scheduled execution with clearInterval().
function boo(){console.log('boo');} var id = setInterval(boo, 2000); clearInterval(id)
Note that both functions accept a pointer to a callback function as a first parameter. They can also accept a string which will be evaluated with eval() but, as you know, eval() is evil, so it should be avoided. And what if you want to pass arguments to the function? In such cases, you can just wrap the function call inside another function.
The code below is valid, but not recommended:
var id = setInterval("alert('boo, boo')", 2000);
This alternative is preferred:
var id = setInterval( function() { alert('boo, boo') }, 2000 );