window.setInterval

  • Revision slug: DOM/window.setInterval
  • Revision title: window.setInterval
  • Revision id: 233970
  • Created:
  • Creator: wooptoo
  • Is current revision? No
  • Comment note on recursion limit; 14 words added

Revision Content

{{ DomRef() }}

Summary

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

Syntax

var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var 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. (Using this syntax is not recommended for the same reasons as using eval())
  • delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func. As with setTimeout, there is a minimum delay enforced.

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

Note: Prior to Gecko 13 {{ geckoRelease("13.0") }}, Gecko passed an extra parameter to the callback routine, indicating the "actual lateness" of the timeout in milliseconds. This non-standard parameter is no longer provided.

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

Callback arguments

If you need to pass an argument to your callback function, but need it to work in Internet Explorer, which doesn't support sending additional parameters with setInterval(), use an anonymous function to call your callback.

Example:

var intervalID = setInterval(function() { funcflashText(); }, 1000);

{{ h3_gecko_minversion("Inactive tabs", "5.0") }}

Starting in Gecko 5.0 {{ geckoRelease("5.0") }}, intervals are clamped to fire no more often than once per second in inactive tabs.

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.

Dangerous usage

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using window.setTimeout.  For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its alloted time.  As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

For such cases, a recursive setTimeout pattern is preferred:

(function loop(){
   setTimeout(function(){

      // logic here

      // recurse
      loop();

  }, 1000);
})();

In the above snippet, a named function loop is declared and is immediately executed.  loop is recursively called inside setTimeout after the logic has completed executing.  While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.


Note: Keep in mind that this approach might exceed the recursion limit.

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 1.0 {{ CompatGeckoDesktop("1") }} 4.0 4.0 1.0
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 1.0 1.0 {{ CompatGeckoMobile("1") }} 6.0 6.0 1.0

 

Specification

{{ DOM0() }}

{{ languages( { "fr": "fr/DOM/window.setInterval", "ja": "ja/DOM/window.setInterval", "pl": "pl/DOM/window.setInterval" } ) }}

Revision Source

<p>{{ DomRef() }}</p>
<h3 name="Summary">Summary</h3>
<p>Calls a function repeatedly, with a fixed time delay between each call to that function.</p>
<h3 name="Syntax">Syntax</h3>
<pre class="eval"><em>var intervalID</em> = window.setInterval(<em>func</em>, <em>delay</em>[, <em>param1</em>, <em>param2</em>, ...]);
<em>var intervalID</em> = window.setInterval(<em>code</em>, <em>delay</em>);
</pre>
<p>where</p>
<ul> <li><code>intervalID</code> is a unique interval ID you can pass to <code><a href="/en/DOM/window.clearInterval" title="en/DOM/window.clearInterval">clearInterval()</a></code>.</li> <li><code>func</code> is the <a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Function">function</a> you want to be called repeatedly.</li> <li><code>code</code> in the alternate syntax, is a string of code you want to be executed repeatedly. (Using this syntax is not recommended for the same reasons as using <a href="/en/JavaScript/Reference/Global_Objects/eval#Don%27t_use_eval!" rel="internal" title="en/JavaScript/Reference/Global Objects/eval#Don't use eval!">eval()</a>)</li> <li><code>delay</code> is the number of milliseconds (thousandths of a second) that the <code>setInterval()</code> function should wait before each call to <code>func</code>. <a href="/en/DOM/window.setTimeout#Minimum_delay_and_timeout_nesting" title="en/DOM/window.setTimeout#Minimum delay and timeout nesting">As with setTimeout</a>, there is a minimum delay enforced.</li>
</ul>
<p>Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer.</p>
<div class="note"><strong>Note:</strong> Prior to Gecko 13 {{ geckoRelease("13.0") }}, Gecko passed an extra parameter to the callback routine, indicating the "actual lateness" of the timeout in milliseconds. This non-standard parameter is no longer provided.</div>
<h3 name="Example">Example</h3>
<pre class="brush: js">var intervalID = window.setInterval(animate, 500);
</pre>
<p>The following example will continue to call the <code>flashtext()</code> function once a second, until you clear the <code>intervalID</code> by clicking the Stop button.</p>
<pre class="brush: js">&lt;html&gt;
&lt;head&gt;
&lt;title&gt;setInterval/clearInterval example&lt;/title&gt;

&lt;script type="text/javascript"&gt;
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);
}
&lt;/script&gt;
&lt;/head&gt;

&lt;body onload="changeColor();"&gt;
&lt;div id="my_box"&gt;
&lt;p&gt;Hello World&lt;/p&gt;
&lt;/div&gt;
&lt;button onclick="stopTextColor();"&gt;Stop&lt;/button&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3 name="Notes">Notes</h3>
<p>The <code>setInterval()</code> function is commonly used to set a delay for functions that are executed again and again, such as animations.</p>
<p>You can cancel the interval using <code><a href="/en/DOM/window.clearInterval" title="en/DOM/window.clearInterval">window.clearInterval()</a></code>.</p>
<p>If you wish to have your function called <em>once</em> after the specified delay, use <code><a href="/en/DOM/window.setTimeout" title="en/DOM/window.setTimeout">window.setTimeout()</a></code>.</p>
<h4>Callback arguments</h4>
<p>If you need to pass an argument to your callback function, but need it to work in Internet Explorer, which doesn't support sending additional parameters with <code>setInterval()</code>, use an anonymous function to call your callback.</p>
<p>Example:</p>
<pre class="brush: js">var intervalID = setInterval(function() { funcflashText(); }, 1000);
</pre>
<p>{{ h3_gecko_minversion("Inactive tabs", "5.0") }}</p>
<p>Starting in Gecko 5.0 {{ geckoRelease("5.0") }}, intervals are clamped to fire no more often than once per second in inactive tabs.</p>
<h3>The '<code>this</code>' problem</h3>
<p>When you pass a method to <code>setInterval()</code> (or any other function, for that matter), it will be invoked with a wrong <code>this</code> value. This problem is explained in detail in the <a href="/en/JavaScript/Reference/Operators/this#Method_binding" title="en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/this_Operator#Method_binding">JavaScript reference</a>.</p>
<h3>Dangerous usage</h3>
<p>If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using <code style="color: inherit; font-weight: inherit; "><a href="/en/DOM/window.setTimeout" style="text-decoration: none; color: rgb(4, 137, 183) !important; cursor: default; " title="en/DOM/window.setTimeout">window.setTimeout</a></code>.  For example, if using <code style="color: inherit; font-weight: inherit; ">setInterval </code>to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its alloted time.  As such, you may find yourself with queued up XHR requests that won't necessarily return in order.</p>
<p>For such cases, a recursive <code>setTimeout </code>pattern is preferred:</p>
<pre class="brush: js">(function loop(){
   setTimeout(function(){

      // logic here

      // recurse
      loop();

  }, 1000);
})();
</pre>
<p>In the above snippet, a named function <code>loop </code>is declared and is immediately executed.  <code>loop </code>is recursively called inside <code>setTimeout </code>after the logic has completed executing.  While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.</p>
<p><br> <strong>Note</strong>: Keep in mind that this approach might exceed the recursion limit.</p><h3>Browser compatibility</h3>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop"> <table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Chrome</th> <th>Firefox (Gecko)</th> <th>Internet Explorer</th> <th>Opera</th> <th>Safari</th> </tr> <tr> <td>Basic support</td> <td>1.0</td> <td>{{ CompatGeckoDesktop("1") }}</td> <td>4.0</td> <td>4.0</td> <td>1.0</td> </tr> </tbody> </table>
</div>
<div id="compat-mobile"> <table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Android</th> <th>Chrome for Android</th> <th>Firefox Mobile (Gecko)</th> <th>IE Mobile</th> <th>Opera Mobile</th> <th>Safari Mobile</th> </tr> <tr> <td>Basic support</td> <td>1.0</td> <td>1.0</td> <td>{{ CompatGeckoMobile("1") }}</td> <td>6.0</td> <td>6.0</td> <td>1.0</td> </tr> </tbody> </table>
</div>
<p> </p>
<h3 name="Specification">Specification</h3>
<p>{{ DOM0() }}</p>
<p>{{ languages( { "fr": "fr/DOM/window.setInterval", "ja": "ja/DOM/window.setInterval", "pl": "pl/DOM/window.setInterval" } ) }}</p>
Revert to this revision