window.setInterval

  • Revision slug: DOM/window.setInterval
  • Revision title: window.setInterval
  • Revision id: 291228
  • Created:
  • Creator: fusionchess
  • Is current revision? No
  • Comment

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.

Examples

Example 1: Generic

var intervalID = window.setInterval(animate, 500);

Example 2: Alternating two colors

The following example will continue to call the flashtext() function once a second, until you clear the intervalID by clicking the Stop button.

<!doctype html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>setInterval/clearInterval example</title>
<script type="text/javascript">
var nIntervId;
 
function changeColor() {
  nIntervId = setInterval(flashText, 500);
}
 
function flashText() {
  var oElem = document.getElementById("my_box");
  oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}
 
function stopTextColor() {
  clearInterval(nIntervId);
}
</script>
</head>
 
<body onload="changeColor();">
<div id="my_box">
<p>Hello World</p>
</div>
<button onclick="stopTextColor();">Stop</button>
</body>
</html>

Example 3: Simulating a typewriter

The following example will delete and re-type simulating a typewriter all the text content of the obtained NodeList which match the specified group of selectors.

<!doctype html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>JavaScript Typewriter - MDN Example</title>
<script type="text/javascript">
function Typewriter (sSelector, nRate) {
    function Excerpt (oItem) {
        this.node = oItem;
        if (!oItem.hasChildNodes()) { return; }
        this.children = Array.prototype.slice.call(oItem.childNodes);
        for (var nChild = 0; nChild < this.children.length; nChild++) {
            oItem.removeChild(this.children[nChild]);
            this.children[nChild] = new Excerpt(this.children[nChild]);
        }
    }

    function scanChildren (oFromPt, nDepth) {
        if (!oFromPt.hasOwnProperty("children")) { return; }
        var oNewPt, bHere = false;
        if (aCoords.length < nDepth + 1) { aCoords[nDepth] = 0; }
        while (bSearching && aCoords[nDepth] < oFromPt.children.length) {
            oNewPt = oFromPt.children[aCoords[nDepth]];
            if (oNewPt.node.nodeValue && (oNewPt.node.nodeType - 1 | 1) === 3) {
                bSearching = false;
                bHere = true;
                oTarget = oNewPt.node;
                sText = oTarget.nodeValue;
                oTarget.nodeValue = "";
            }
            scanChildren(oNewPt, nDepth + 1);
            oFromPt.node.appendChild(oNewPt.node);
            if (bSearching || bHere) { aCoords[nDepth]++; }
        }
        if (bSearching) { aCoords.length--; }
    }

    function typeChar () {
        if (sText.length === 0) {
            bSearching = true;
            scanChildren(aMap[nIdx], 0);
            if (aCoords.length === 0 && nIdx++ === aMap.length - 1) {
                clearInterval(nDrawingUp);
                bTyping = false;
                bEnd = true;
                aMap.length = nIdx = 0;
            }
        }
        if (!oTarget) { return; }
        oTarget.nodeValue += sText.charAt(0);
        sText = sText.slice(1);
    }

    var
        nDrawingUp, oTarget, bTyping = false, bEnd = true, bSearching = true,
        nIdx = 0, sText = "", aMap = [], aCoords = [];

    this.play = function () {
        if (bTyping) { return; }
        if (bEnd) {
            var aItems = document.querySelectorAll(sSelector);
            if (aItems.length === 0) { return; }
            for (var nItem = 0; nItem < aItems.length; nItem++) {
                aMap.push(new Excerpt(aItems[nItem]));
                /* uncomment the following line if you have previously hidden your elements via CSS: */
                // aItems[nItem].style.visibility = "visible";
            }
            bEnd = false;
        }
        nDrawingUp = setInterval(typeChar, nRate || 100);
        bTyping = true;
    };

    this.pause = function () {
        clearInterval(nDrawingUp);
        bTyping = false;
    };
}

/* usage: */
var oTWExample1 = new Typewriter(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15);

/* default frame rate is 100: */
var oTWExample2 = new Typewriter("#controls");

onload = function () {
    oTWExample1.play();
    oTWExample2.play();
};
</script>
<style type="text/css">
span.intLink, a, a:visited  {
    cursor: pointer;
    color: #000000;
    text-decoration: underline;
}

#info {
  width: 180px;
  height: 150px;
  float: right;
  background-color: #eeeeff;
  padding: 4px;
  overflow: auto;
  font-size: 12px;
  margin: 4px;
  border-radius: 5px;
  /* visibility: hidden; */
}
</style>
</head>

<body>

<p id="copyleft" style="font-style: italic; font-size: 12px; text-align: center;">CopyLeft 2012 by <a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a></p>
<p id="controls" style="text-align: center;">[&nbsp;<span class="intLink" onclick="oTWExample1.play();">Play</span> | <span class="intLink" onclick="oTWExample1.pause();">Pause</span>&nbsp;]</p>
<div id="info">
Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt.
</div>
<h1>JavaScript Typewriter</h1>

<div id="article">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p>
<form name="myForm">
<p>Phasellus ac nisl lorem: <input type="text" name="email" /><br />
<textarea name="comment" style="width: 400px; height: 200px;">Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</textarea></p>
<p><input type="submit" value="Send" />
</form>
<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent bibendum condimentum feugiat.</p>
<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p>
</div>
</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.

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 id="Summary" name="Summary">Summary</h3>
<p>Calls a function repeatedly, with a fixed time delay between each call to that function.</p>
<h3 id="Syntax" 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 id="Example" name="Example">Examples</h3>
<h4 id="Example_1:_Generic">Example 1: Generic</h4>
<pre class="brush: js">
var intervalID = window.setInterval(animate, 500);
</pre>
<h4 id="Example_2:_Alternating_two_colors">Example 2: Alternating two colors</h4>
<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: html">
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /&gt;
&lt;title&gt;setInterval/clearInterval example&lt;/title&gt;
&lt;script type="text/javascript"&gt;
var nIntervId;
&nbsp;
function changeColor() {
&nbsp; nIntervId = setInterval(flashText, 500);
}
&nbsp;
function flashText() {
&nbsp; var oElem = document.getElementById("my_box");
&nbsp; oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}
&nbsp;
function stopTextColor() {
&nbsp; clearInterval(nIntervId);
}
&lt;/script&gt;
&lt;/head&gt;
&nbsp;
&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>
<h4 id="Example_3:_Simulating_a_typewriter">Example 3: Simulating a typewriter</h4>
<p>The following example will delete and re-type simulating a <em>typewriter</em> all the text content of the obtained <a href="/en-US/docs/DOM/NodeList" title="/en-US/docs/DOM/NodeList"><code>NodeList</code></a> which match the specified group of selectors.</p>
<div style="height: 600px; overflow: auto;">
  <pre class="brush: html">
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /&gt;
&lt;title&gt;JavaScript Typewriter - MDN Example&lt;/title&gt;
&lt;script type="text/javascript"&gt;
function Typewriter (sSelector, nRate) {
&nbsp;&nbsp; &nbsp;function Excerpt (oItem) {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;this.node = oItem;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (!oItem.hasChildNodes()) { return; }
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;this.children = Array.prototype.slice.call(oItem.childNodes);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;for (var nChild = 0; nChild &lt; this.children.length; nChild++) {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;oItem.removeChild(this.children[nChild]);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;this.children[nChild] = new Excerpt(this.children[nChild]);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}
&nbsp;&nbsp; &nbsp;}

&nbsp;&nbsp; &nbsp;function scanChildren (oFromPt, nDepth) {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (!oFromPt.hasOwnProperty("children")) { return; }
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;var oNewPt, bHere = false;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (aCoords.length &lt; nDepth + 1) { aCoords[nDepth] = 0; }
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;while (bSearching &amp;&amp; aCoords[nDepth] &lt; oFromPt.children.length) {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;oNewPt = oFromPt.children[aCoords[nDepth]];
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (oNewPt.node.nodeValue &amp;&amp; (oNewPt.node.nodeType - 1 | 1) === 3) {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;bSearching = false;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;bHere = true;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;oTarget = oNewPt.node;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;sText = oTarget.nodeValue;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;oTarget.nodeValue = "";
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;scanChildren(oNewPt, nDepth + 1);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;oFromPt.node.appendChild(oNewPt.node);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (bSearching || bHere) { aCoords[nDepth]++; }
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (bSearching) { aCoords.length--; }
&nbsp;&nbsp; &nbsp;}

&nbsp;&nbsp; &nbsp;function typeChar () {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (sText.length === 0) {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;bSearching = true;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;scanChildren(aMap[nIdx], 0);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (aCoords.length === 0 &amp;&amp; nIdx++ === aMap.length - 1) {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;clearInterval(nDrawingUp);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;bTyping = false;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;bEnd = true;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;aMap.length = nIdx = 0;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (!oTarget) { return; }
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;oTarget.nodeValue += sText.charAt(0);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;sText = sText.slice(1);
&nbsp;&nbsp; &nbsp;}

&nbsp;&nbsp; &nbsp;var
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;nDrawingUp, oTarget, bTyping = false, bEnd = true, bSearching = true,
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;nIdx = 0, sText = "", aMap = [], aCoords = [];

&nbsp;&nbsp; &nbsp;this.play = function () {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (bTyping) { return; }
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (bEnd) {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;var aItems = document.querySelectorAll(sSelector);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if (aItems.length === 0) { return; }
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;for (var nItem = 0; nItem &lt; aItems.length; nItem++) {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;aMap.push(new Excerpt(aItems[nItem]));
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;/* uncomment the following line if you have previously hidden your elements via CSS: */
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;// aItems[nItem].style.visibility = "visible";
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;bEnd = false;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;nDrawingUp = setInterval(typeChar, nRate || 100);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;bTyping = true;
&nbsp;&nbsp; &nbsp;};

&nbsp;&nbsp; &nbsp;this.pause = function () {
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;clearInterval(nDrawingUp);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;bTyping = false;
&nbsp;&nbsp; &nbsp;};
}

/* usage: */
var oTWExample1 = new Typewriter(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15);

/* default frame rate is 100: */
var oTWExample2 = new Typewriter("#controls");

onload = function () {
&nbsp;&nbsp; &nbsp;oTWExample1.play();
&nbsp;&nbsp; &nbsp;oTWExample2.play();
};
&lt;/script&gt;
&lt;style type="text/css"&gt;
span.intLink, a, a:visited&nbsp; {
&nbsp;&nbsp;&nbsp; cursor: pointer;
&nbsp;&nbsp;&nbsp; color: #000000;
&nbsp;&nbsp;&nbsp; text-decoration: underline;
}

#info {
&nbsp; width: 180px;
&nbsp; height: 150px;
&nbsp; float: right;
&nbsp; background-color: #eeeeff;
&nbsp; padding: 4px;
&nbsp; overflow: auto;
&nbsp; font-size: 12px;
&nbsp; margin: 4px;
&nbsp; border-radius: 5px;
&nbsp; /* visibility: hidden; */
}
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;p id="copyleft" style="font-style: italic; font-size: 12px; text-align: center;"&gt;CopyLeft 2012 by &lt;a href="https://developer.mozilla.org/" target="_blank"&gt;Mozilla Developer Network&lt;/a&gt;&lt;/p&gt;
&lt;p id="controls" style="text-align: center;"&gt;[&amp;nbsp;&lt;span class="intLink" onclick="oTWExample1.play();"&gt;Play&lt;/span&gt; | &lt;span class="intLink" onclick="oTWExample1.pause();"&gt;Pause&lt;/span&gt;&amp;nbsp;]&lt;/p&gt;
&lt;div id="info"&gt;
Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt.
&lt;/div&gt;
&lt;h1&gt;JavaScript Typewriter&lt;/h1&gt;

&lt;div id="article"&gt;
&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.&lt;/p&gt;
&lt;form name="myForm"&gt;
&lt;p&gt;Phasellus ac nisl lorem: &lt;input type="text" name="email" /&gt;&lt;br /&gt;
&lt;textarea name="comment" style="width: 400px; height: 200px;"&gt;Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.&lt;/textarea&gt;&lt;/p&gt;
&lt;p&gt;&lt;input type="submit" value="Send" /&gt;
&lt;/form&gt;
&lt;p&gt;Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent bibendum condimentum feugiat.&lt;/p&gt;
&lt;p&gt;Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.&lt;/p&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
</div>
<h3 id="Notes" 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 id="Callback_arguments">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 id="The_&quot;this&quot;_problem">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 id="Dangerous_usage">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&nbsp;<code><a href="/en/DOM/window.setTimeout" title="en/DOM/window.setTimeout">window.setTimeout</a></code>. For example, if using&nbsp;<code style="color: inherit; font-weight: inherit; ">setInterval&nbsp;</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. &nbsp;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&nbsp;</code>pattern is preferred:</p>
<pre class="brush: js">
(function loop(){
   setTimeout(function(){

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// logic here

      // recurse
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;loop();

&nbsp;&nbsp;}, 1000);
})();
</pre>
<p>In the above snippet, a named function <code>loop </code>is declared and is immediately executed. &nbsp;<code>loop </code>is recursively called inside <code>setTimeout </code>after the logic has completed executing. &nbsp;While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.</p>
<h3 id="Browser_compatibility">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>&nbsp;</p>
<h3 id="Specification" 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