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
<html>
<head>
<script type="text/javascript">
function delayedAlert()
{
var t=setTimeout("alert('You pressed the button 5 seconds ago!')",5000)
}
</script>
</head>
<body>
<form>
<input type="button" value="Display Delayed Alert"
onClick="delayedAlert();">
</form>
</body>
</html>
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.
Want automatic updates?
Subscribe to our RSS feed
or
Get Email Updates
sent directly to your inbox!
Currently rated 5.0 by 4 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5