DOM:window.setInterval
From MDC
Contents |
[edit] Summary
Calls a function repeatedly, with a fixed time delay between each call to that function.
[edit] Syntax
intervalID = window.setInterval(func, delay[, param1, param2, ...]); intervalID = window.setInterval(code, delay);
where
-
intervalIDis a unique interval ID you can pass toclearInterval(). -
funcis the function you want to be called repeatedly. -
codein the alternate syntax, is a string of code you want to be executed repeatedly. -
delayis the number of milliseconds (thousandths of a second) that thesetInterval()function should wait before each call tofunc.
Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer.
[edit] Example
var intervalID = window.setInterval(animate, 500);
The following example will continue to call the flashtext() function once a second, until you clear the intervalID by clicking the Stop button.
<html>
<head>
<title>setInterval/clearInterval example</title>
<script type="text/javascript">
var intervalID;
function changeColor()
{
intervalID = setInterval(flashText, 1000);
}
function flashText()
{
var elem = document.getElementById("my_box");
if (elem.style.color == 'red')
{
elem.style.color = 'blue';
}
else
{
elem.style.color = 'red';
}
}
function stopTextColor()
{
clearInterval(intervalID);
}
</script>
</head>
<body onload="changeColor();">
<div id="my_box">
<p>Hello World</p>
</div>
<button onclick="stopTextColor();">Stop</button>
</body>
</html>
[edit] Notes
The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations.
You can cancel the interval using window.clearInterval().
If you wish to have your function called once after the specified delay, use window.setTimeout().
[edit] The 'this' problem
When you pass a method to setInterval() (or any other function, for that matter), it will be invoked with a wrong this value. This problem is explained in detail in the JavaScript reference.
[edit] Specification
DOM Level 0. Not part of any standard.