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 setInterval() method works, and give a real world example. You may find the details of setTimeout() method in JavaScript setTimeout Function - JavaScript Timing Events
setInterval()
window.setInterval() method allows you to specify a piece of JavaScript code (expression) that will be triggered again and again in every specified number of miliseconds.
Syntax
var t = setInterval ( expression, timeout );
The setInterval() method returns a numeric timeout ID which can be used to refer the time interval to use with clearInterval method. The first parameter (expression) of setInterval() 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
<script type="text/javascript">
setInterval("doSomething()", 5000);
function doSomething()
{
// do something
}
</script>
The doSomething() function will be called in every 5 seconds until it is cancelled.
clearInterval()
If you want to cancel a setInterval() then you need to call clearInterval(), passing the internal ID returned by the call to setInterval().
Currently rated 5.0 by 4 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5