The Wayback Machine - https://web.archive.org/web/20080902061528/http://developer.mozilla.org:80/en/DOM/window.setInterval

Mozilla.com

  1. MDC
  2. Main Page
  3. DOM
  4. window.setInterval

Some features of this site require JavaScript.

window.setInterval

« Gecko DOM Reference

Summary

Calls a function repeatedly, with a fixed time delay between each call to that function.

Syntax

intervalID = window.setInterval(func, delay[, param1, param2, ...]);
intervalID = window.setInterval(code, delay);

where

  • intervalID is a unique interval ID you can pass to clearInterval().
  • func is the function you want to be called repeatedly.
  • code in the alternate syntax, is a string of code you want to be executed repeatedly.
  • delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func.

Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer.

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>

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().

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.

Specification

DOM Level 0. Not part of any standard.

Page last modified 23:11, 20 Mar 2008 by Ceth?

Files (0)

 
 
 
Morty Proxy This is a proxified and sanitized view of the page, visit original site.