Window.setInterval

  • Revision slug: Web/API/window.setInterval
  • Revision title: window.setInterval
  • Revision id: 424085
  • Created:
  • Creator: fusionchess
  • Is current revision? No
  • Comment

Revision Content

{{DomRef}}

Summary

Calls a function or executes a code snippet 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);
  • 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. If you want to enable this functionality on that browser you must use a compatibility code (see the Callback arguments paragraph).

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 charset="UTF-8" />
<title>setInterval/clearInterval example</title>
<script>
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 NodeList which match a specified group of selectors.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>JavaScript Typewriter - MDN Example</title>
<script>
function Typewriter (sSelector, nRate) {

  function clean () {
    clearInterval(nIntervId);
    bTyping = false;
    bStart = true;
    oCurrent = null;
    aSheets.length = nIdx = 0;
  }

  function scroll (oSheet, nPos, bEraseAndStop) {
    if (!oSheet.hasOwnProperty("parts") || aMap.length < nPos) { return true; }

    var oRel, bExit = false;

    if (aMap.length === nPos) { aMap.push(0); }

    while (aMap[nPos] < oSheet.parts.length) {
      oRel = oSheet.parts[aMap[nPos]];

      scroll(oRel, nPos + 1, bEraseAndStop) ? aMap[nPos]++ : bExit = true;

      if (bEraseAndStop && (oRel.ref.nodeType - 1 | 1) === 3 && oRel.ref.nodeValue) {
        bExit = true;
        oCurrent = oRel.ref;
        sPart = oCurrent.nodeValue;
        oCurrent.nodeValue = "";
      }

      oSheet.ref.appendChild(oRel.ref);
      if (bExit) { return false; }
    }

    aMap.length--;
    return true;
  }

  function typewrite () {
    if (sPart.length === 0 && scroll(aSheets[nIdx], 0, true) && nIdx++ === aSheets.length - 1) { clean(); return; }

    oCurrent.nodeValue += sPart.charAt(0);
    sPart = sPart.slice(1);
  }

  function Sheet (oNode) {
    this.ref = oNode;
    if (!oNode.hasChildNodes()) { return; }
    this.parts = Array.prototype.slice.call(oNode.childNodes);

    for (var nChild = 0; nChild < this.parts.length; nChild++) {
      oNode.removeChild(this.parts[nChild]);
      this.parts[nChild] = new Sheet(this.parts[nChild]);
    }
  }

  var
    nIntervId, oCurrent = null, bTyping = false, bStart = true,
    nIdx = 0, sPart = "", aSheets = [], aMap = [];

  this.rate = nRate || 100;
 
  this.play = function () {
    if (bTyping) { return; }
    if (bStart) {
      var aItems = document.querySelectorAll(sSelector);

      if (aItems.length === 0) { return; }
      for (var nItem = 0; nItem < aItems.length; nItem++) {
        aSheets.push(new Sheet(aItems[nItem]));
        /* Uncomment the following line if you have previously hidden your elements via CSS: */
        // aItems[nItem].style.visibility = "visible";
      }

      bStart = false;
    }

    nIntervId = setInterval(typewrite, this.rate);
    bTyping = true;
  };
 
  this.pause = function () {
    clearInterval(nIntervId);
    bTyping = false;
  };
 
  this.terminate = function () {
    oCurrent.nodeValue += sPart;
    sPart = "";
    for (nIdx; nIdx < aSheets.length; scroll(aSheets[nIdx++], 0, false));
    clean();
  };
}
 
/* usage: */
var oTWExample1 = new Typewriter(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15);
 
/* default frame rate is 100: */
var oTWExample2 = new Typewriter("#controls");

/* you can also change the frame rate value modifying the "rate" property; for example: */
// oTWExample2.rate = 150;
 
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> | <span class="intLink" onclick="oTWExample1.terminate();">Terminate</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 bibStartum quis. Cras adipiscing ultricies fermentum. Praesent bibStartum 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>

View this demo in action. See also: clearInterval().

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 (neither with setTimeout() or setInterval()) you can include this IE-specific compatibility code which will enable the HTML5 standard parameters passage functionality in that browser for both timers just by inserting it at the beginning of your scripts.

/*\
|*|
|*|  IE-specific polyfill which enables the passage of arbitrary arguments to the
|*|  callback functions of javascript timers (HTML5 standard syntax).
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
|*|
|*|  Syntax:
|*|  var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
|*|  var timeoutID = window.setTimeout(code, delay);
|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
|*|  var intervalID = window.setInterval(code, delay);
|*|
\*/

if (document.all && !window.setTimeout.isPolyfill) {
  var __nativeST__ = window.setTimeout;
  window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
    var aArgs = Array.prototype.slice.call(arguments, 2);
    return __nativeST__(vCallback instanceof Function ? function () {
      vCallback.apply(null, aArgs);
    } : vCallback, nDelay);
  };
  window.setTimeout.isPolyfill = true;
}

if (document.all && !window.setInterval.isPolyfill) {
  var __nativeSI__ = window.setInterval;
  window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
    var aArgs = Array.prototype.slice.call(arguments, 2);
    return __nativeSI__(vCallback instanceof Function ? function () {
      vCallback.apply(null, aArgs);
    } : vCallback, nDelay);
  };
  window.setInterval.isPolyfill = true;
}

Another possibility is to use an anonymous function to call your callback, but this solution is a bit more expensive. Example:

var intervalID = setInterval(function() { myFunc("one", "two", "three"); }, 1000);

Yet another possibility is to use function's bind. Example:

var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 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.

Explanation

Code executed by setInterval() is run in a separate execution context to the function from which it was called. As a consequence, the this keyword for the called function will be set to the window (or global) object, it will not be the same as the this value for the function that called setTimeout. See the following example (which for praticity uses setTimeout() instead of setInterval() – the problem in fact is the same for both timers):

myArray = ["zero", "one", "two"];

myArray.myMethod = function (sProperty) {
    alert(arguments.length > 0 ? this[sProperty] : this);
};

myArray.myMethod(); // prints "zero,one,two"
myArray.myMethod(1); // prints "one"
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds
// let's try to pass the 'this' object
setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error

As you can see there are no ways to pass the this object to the callback function.

A possible solution

A possible way to solve the "this" problem is to replace the two native setTimeout() or setInterval() global functions with two non-native ones which will enable their invocation through the Function.prototype.call method. The following example shows a possible replacement:

// Enable the passage of the 'this' object through the JavaScript timers

var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;

window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeST__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};

window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeSI__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};
Note: This two replacements will also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as non-standard-compliant polyfills also. See the callback arguments paragraph for a standard-compliant polyfill.

New feature test:

myArray = ["zero", "one", "two"];

myArray.myMethod = function (sProperty) {
    alert(arguments.length > 0 ? this[sProperty] : this);
};

setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but...
setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds

Another, more complex, solution for the this problem is the following little framework.

Note: JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called.

A little framework

Sometimes a page uses dozens and dozens of animations. In such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the clearTimeout() function. A possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them.
Here is a possible and minimalist example of such abstraction, which for this reason we named MiniDaemon.

Note: For a more complex but still modular modular version of it (Daemon) see JavaScript Daemons Management. This more complex version is nothing but a big and scalable collection of methods for the Daemon constructor. But the Daemon constructor itself is nothing but a clone of MiniDaemon with an added support for init and onstart functions declarable during the instantiation of the daemon. So the MiniDaemon framework will remain the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it.

The architecture of this constructor explicitly avoids the use of closures. It also offers an alternative way to pass the this object to the callback function (see The "this" problem for details).

minidaemon.js

/*\
|*|
|*|  MiniDaemon - Mozilla Developer Network - ver. 1.0 rev. 1
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
|*|  https://developer.mozilla.org/User:fusionchess
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
\*/
 
function MiniDaemon (oOwner, fTask, nRate, nLen) {
  if (!(this && this instanceof MiniDaemon)) { return; }
  if (arguments.length < 2) { throw new TypeError("MiniDaemon - not enough arguments"); }
  if (oOwner) { this.owner = oOwner; }
  this.task = fTask;
  if (isFinite(nRate) && nRate > 0) { this.rate = Math.floor(nRate); }
  if (nLen > 0) { this.length = Math.floor(nLen); }
}
 
MiniDaemon.prototype.owner = null;
MiniDaemon.prototype.task = null;
MiniDaemon.prototype.rate = 100;
MiniDaemon.prototype.length = Infinity;
 
  /* These properties should be read-only */
 
MiniDaemon.prototype.SESSION = -1;
MiniDaemon.prototype.INDEX = 0;
MiniDaemon.prototype.PAUSED = true;
MiniDaemon.prototype.BACKW = true;
 
  /* Global methods */
 
MiniDaemon.forceCall = function (oDmn) {
  oDmn.INDEX += oDmn.BACKW ? -1 : 1;
  if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; }
  return true;
};
 
  /* Instances methods */
 
MiniDaemon.prototype.isAtEnd = function () {
  return this.BACKW ? isFinite(this.length) && this.INDEX < 1 : this.INDEX + 1 > this.length;
};
 
MiniDaemon.prototype.synchronize = function () {
  if (this.PAUSED) { return; }
  clearInterval(this.SESSION);
  this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this);
};
 
MiniDaemon.prototype.pause = function () {
  clearInterval(this.SESSION);
  this.PAUSED = true;
};
 
MiniDaemon.prototype.start = function (bReverse) {
  var bBackw = Boolean(bReverse);
  if (this.BACKW === bBackw && (this.isAtEnd() || !this.PAUSED)) { return; }
  this.BACKW = bBackw;
  this.PAUSED = false;
  this.synchronize();
};
Note: This small framework utilises the passage of arguments to the callback function. If you want to work on it with browsers which natively do not support this feature, use the polyfill proposed here.

Syntax

var myDaemon = new MiniDaemon(thisObject, callback[, rate[, length]]);

Description

Returns a JavaScript Object containing all informations needed by an animation (like the this object, the callback function, the length, the frame-rate).

Parameters

thisObject
The this object on which will be called the callback function. It can be an object or null.
callback
The function which will be invoked repeatedly. It will be called with three parameters: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is increasing or decreasing). It will be something like callback.call(thisObject, index, length, backwards). If the callback function returns a false value the daemon will be paused.
rate (optional)
The time lapse (in number of milliseconds) between each invocation. The default value is 100.
length (optional)
The total number of invocations. It can be a positive integer or Infinity. The default value is Infinity.

MiniDaemon instances properties

myDaemon.owner
The this object on which is executed the daemon (read/write). It can be an object or null.
myDaemon.task
The function which will be repeatedly invoked (read/write). It will be called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon will be paused.
myDaemon.rate
The time lapse (in number of milliseconds) between each invocation (read/write).
myDaemon.length
The total number of invocations. It can be a positive integer or Infinity (read/write).

MiniDaemon instances methods

myDaemon.isAtEnd()
Returns a boolean expressing whether the daemon is at the start/end position or not.
myDaemon.synchronize()
Synchronize the timer of a started daemon with the time of its invocation.
myDaemon.pause()
Pauses the daemon.
myDaemon.start([reverse])
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).

MiniDaemon global object methods

MiniDaemon.forceCall(minidaemon)
Forces a single callback to the minidaemon.task function regardless of the fact that the end has been reached or not. In any case the internal INDEX property will be increased/decreased (depending on the actual direction of the process).

Example usage

your HTML page:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>MiniDaemin Example - MDN</title>
<script type="text/javascript" src="minidaemon.js"></script>
<style type="text/css">
#sample_div {
  visibility: hidden;
}
</style>
</head>

<body>
<p><input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" /> <input type="button" onclick="fadeInOut.start(true);" value="fade out"> <input type="button" onclick="fadeInOut.pause();" value="pause" /></p>
<div id="sample_div">Some text here</div>

<script type="text/javascript">
function opacity (nIndex, nLength, bBackwards) {
  this.style.opacity = nIndex / nLength;
  if (bBackwards ? nIndex === 0 : nIndex === 1) {
    this.style.visibility = bBackwards ? "hidden" : "visible";
  }
}

var fadeInOut = new MiniDaemon(document.getElementById("sample_div"), opacity, 300, 8);
</script>
</body>
</html>

View this example in action

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

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
Supports parameters for callback*1 {{CompatVersionUnknown}} {{CompatVersionUnknown}} 10.0 {{CompatVersionUnknown}} {{CompatUnknown}}
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
Supports parameters for callback*1 {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}

*1 Whether it supports the optional parameters when in its first form or not.

Specification

{{DOM0}}

See also

  • JavaScript timers
  • {{domxref("window.setTimeout")}}
  • {{domxref("window.clearTimeout")}}
  • {{domxref("window.clearInterval")}}
  • {{domxref("window.requestAnimationFrame")}}
  • Daemons management

Revision Source

<div>
  {{DomRef}}</div>
<h2 id="Summary" name="Summary">Summary</h2>
<p>Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.</p>
<h2 id="Syntax" name="Syntax">Syntax</h2>
<pre class="syntaxbox">
<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>
<ul>
  <li><code>intervalID</code> is a unique interval ID you can pass to <code><a href="/en-US/docs/DOM/window.clearInterval">clearInterval()</a></code>.</li>
  <li><code>func</code> is the <a href="/en-US/docs/JavaScript/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 <strong>not recommended</strong> for the same reasons as using <a href="/en-US/docs/JavaScript/Reference/Global_Objects/eval#Don%27t_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-US/docs/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. If you want to enable this functionality on that browser you must use a compatibility code (see the <a href="#Callback_arguments">Callback arguments</a> paragraph).</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>
<h2 id="Example" name="Example">Examples</h2>
<h3 id="Example_1.3A_Generic">Example 1: Generic</h3>
<pre class="brush:js">
var intervalID = window.setInterval(animate, 500);
</pre>
<h3 id="Example_2.3A_Alternating_two_colors">Example 2: Alternating two colors</h3>
<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 charset="UTF-8" /&gt;
&lt;title&gt;setInterval/clearInterval example&lt;/title&gt;
&lt;script&gt;
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);
}
&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 id="Example_3.3A_Simulating_a_typewriter">Example 3: Simulating a typewriter</h3>
<p>The following example will delete and re-type simulating a <em>typewriter</em> all the text content of the <a href="/en-US/docs/DOM/NodeList" title="DOM/NodeList"><code>NodeList</code></a> which match a specified group of selectors.</p>
<pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;
&lt;title&gt;JavaScript Typewriter - MDN Example&lt;/title&gt;
&lt;script&gt;
function Typewriter (sSelector, nRate) {

  function clean () {
    clearInterval(nIntervId);
    bTyping = false;
    bStart = true;
    oCurrent = null;
    aSheets.length = nIdx = 0;
  }

  function scroll (oSheet, nPos, bEraseAndStop) {
    if (!oSheet.hasOwnProperty("parts") || aMap.length &lt; nPos) { return true; }

    var oRel, bExit = false;

    if (aMap.length === nPos) { aMap.push(0); }

    while (aMap[nPos] &lt; oSheet.parts.length) {
      oRel = oSheet.parts[aMap[nPos]];

      scroll(oRel, nPos + 1, bEraseAndStop) ? aMap[nPos]++ : bExit = true;

      if (bEraseAndStop &amp;&amp; (oRel.ref.nodeType - 1 | 1) === 3 &amp;&amp; oRel.ref.nodeValue) {
        bExit = true;
        oCurrent = oRel.ref;
        sPart = oCurrent.nodeValue;
        oCurrent.nodeValue = "";
      }

      oSheet.ref.appendChild(oRel.ref);
      if (bExit) { return false; }
    }

    aMap.length--;
    return true;
  }

  function typewrite () {
    if (sPart.length === 0 &amp;&amp; scroll(aSheets[nIdx], 0, true) &amp;&amp; nIdx++ === aSheets.length - 1) { clean(); return; }

    oCurrent.nodeValue += sPart.charAt(0);
    sPart = sPart.slice(1);
  }

  function Sheet (oNode) {
    this.ref = oNode;
    if (!oNode.hasChildNodes()) { return; }
    this.parts = Array.prototype.slice.call(oNode.childNodes);

    for (var nChild = 0; nChild &lt; this.parts.length; nChild++) {
      oNode.removeChild(this.parts[nChild]);
      this.parts[nChild] = new Sheet(this.parts[nChild]);
    }
  }

  var
    nIntervId, oCurrent = null, bTyping = false, bStart = true,
    nIdx = 0, sPart = "", aSheets = [], aMap = [];

  this.rate = nRate || 100;
 
  this.play = function () {
    if (bTyping) { return; }
    if (bStart) {
      var aItems = document.querySelectorAll(sSelector);

      if (aItems.length === 0) { return; }
      for (var nItem = 0; nItem &lt; aItems.length; nItem++) {
        aSheets.push(new Sheet(aItems[nItem]));
        /* Uncomment the following line if you have previously hidden your elements via CSS: */
        // aItems[nItem].style.visibility = "visible";
      }

      bStart = false;
    }

    nIntervId = setInterval(typewrite, this.rate);
    bTyping = true;
  };
 
  this.pause = function () {
    clearInterval(nIntervId);
    bTyping = false;
  };
 
  this.terminate = function () {
    oCurrent.nodeValue += sPart;
    sPart = "";
    for (nIdx; nIdx &lt; aSheets.length; scroll(aSheets[nIdx++], 0, false));
    clean();
  };
}
 
/* usage: */
var oTWExample1 = new Typewriter(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15);
 
/* default frame rate is 100: */
var oTWExample2 = new Typewriter("#controls");

/* you can also change the frame rate value modifying the "rate" property; for example: */
// oTWExample2.rate = 150;
 
onload = function () {
  oTWExample1.play();
  oTWExample2.play();
};
&lt;/script&gt;
&lt;style type="text/css"&gt;
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; */
}
&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; | &lt;span class="intLink" onclick="oTWExample1.terminate();"&gt;Terminate&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 bibStartum quis. Cras adipiscing ultricies fermentum. Praesent bibStartum 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>
<p><a href="/files/3997/typewriter.html" title="View this demo in action">View this demo in action</a>. See also: <a href="/en-US/docs/DOM/window.clearInterval" title="DOM/window.clearInterval"><code>clearInterval()</code></a>.</p>
<h2 id="Callback_arguments">Callback arguments</h2>
<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 (neither with <code>setTimeout()</code> or <code>setInterval()</code>) you can include this <em>IE-specific</em> compatibility code which will enable the HTML5 standard parameters passage functionality in that browser for both timers just by inserting it at the beginning of your scripts.</p>
<pre class="brush:js">
/*\
|*|
|*|  IE-specific polyfill which enables the passage of arbitrary arguments to the
|*|  callback functions of javascript timers (HTML5 standard syntax).
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
|*|
|*|  Syntax:
|*|  var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
|*|  var timeoutID = window.setTimeout(code, delay);
|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
|*|  var intervalID = window.setInterval(code, delay);
|*|
\*/

if (document.all &amp;&amp; !window.setTimeout.isPolyfill) {
  var __nativeST__ = window.setTimeout;
  window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
    var aArgs = Array.prototype.slice.call(arguments, 2);
    return __nativeST__(vCallback instanceof Function ? function () {
      vCallback.apply(null, aArgs);
    } : vCallback, nDelay);
  };
  window.setTimeout.isPolyfill = true;
}

if (document.all &amp;&amp; !window.setInterval.isPolyfill) {
  var __nativeSI__ = window.setInterval;
  window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
    var aArgs = Array.prototype.slice.call(arguments, 2);
    return __nativeSI__(vCallback instanceof Function ? function () {
      vCallback.apply(null, aArgs);
    } : vCallback, nDelay);
  };
  window.setInterval.isPolyfill = true;
}
</pre>
<p>Another possibility is to use an anonymous function to call your callback, but this solution is a bit more expensive. Example:</p>
<pre class="brush:js">
var intervalID = setInterval(function() { myFunc("one", "two", "three"); }, 1000);</pre>
<p>Yet another possibility is to use <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="JavaScript/Reference/Global_Objects/Function/bind">function's bind</a>. Example:</p>
<pre class="brush:js">
var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 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>
<h2 id="The_.22this.22_problem">The "<a href="/en-US/docs/JavaScript/Reference/Operators/this" title="JavaScript/Reference/Operators/this"><code>this</code></a>" problem</h2>
<p>When you pass a method to <code>setInterval()</code> (or any other function, for that matter), it will be invoked with a wrong <a href="/en-US/docs/JavaScript/Reference/Operators/this" title="JavaScript/Reference/Operators/this"><code>this</code></a> value. This problem is explained in detail in the <a href="/en-US/docs/JavaScript/Reference/Operators/this#Method_binding" title="JavaScript/Reference/Operators/Special_Operators/this_Operator#Method_binding">JavaScript reference</a>.</p>
<h3 id="Explanation">Explanation</h3>
<p>Code executed by <code>setInterval()</code> is run in a separate execution context to the function from which it was called. As a consequence, the <a href="/en-US/docs/JavaScript/Reference/Operators/this" title="JavaScript/Reference/Operators/this"><code>this</code></a> keyword for the called function will be set to the <code>window</code> (or <code>global</code>) object, it will not be the same as the <code>this</code> value for the function that called <code>setTimeout</code>. See the following example (which for praticity uses <code>setTimeout()</code> instead of <code>setInterval()</code> – the problem in fact is the same for both timers):</p>
<pre class="brush:js">
myArray = ["zero", "one", "two"];

myArray.myMethod = function (sProperty) {
    alert(arguments.length &gt; 0 ? this[sProperty] : this);
};

myArray.myMethod(); // prints "zero,one,two"
myArray.myMethod(1); // prints "one"
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds
// let's try to pass the 'this' object
setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error</pre>
<p>As you can see there are no ways to pass the <code>this</code> object to the callback function.</p>
<h3 id="A_possible_solution">A possible solution</h3>
<p>A possible way to solve the "<code>this</code>" problem is to replace the two native <code>setTimeout()</code> or <code>setInterval()</code> global functions with two <em>non-native</em> ones which will enable their invocation through the <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/call" title="JavaScript/Reference/Global_Objects/Function/call"><code>Function.prototype.call</code></a> method. The following example shows a possible replacement:</p>
<pre class="brush:js">
// Enable the passage of the 'this' object through the JavaScript timers

var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;

window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeST__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};

window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeSI__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};</pre>
<div class="note">
  <strong>Note:</strong> This two replacements will also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as <em>non-standard-compliant</em> polyfills also. See the <a href="#Callback_arguments">callback arguments paragraph</a> for a <em>standard-compliant</em> polyfill.</div>
<p>New feature test:</p>
<pre class="brush:js">
myArray = ["zero", "one", "two"];

myArray.myMethod = function (sProperty) {
    alert(arguments.length &gt; 0 ? this[sProperty] : this);
};

setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but...
setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds
</pre>
<p><strong>Another, more complex, solution for <em>the </em><a href="/en-US/docs/JavaScript/Reference/Operators/this"><code><em>this</em></code></a> <em>problem</em> is <a href="#A_little_framework" title="A little framework">the following little framework</a>.</strong></p>
<div class="note">
  <strong>Note:</strong> JavaScript 1.8.5 introduces the <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="JavaScript/Reference/Global Objects/Function/bind">Function.prototype.bind()</a></code> method, which lets you specify the value that should be used as <code>this</code> for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called.</div>
<h2 id="A_little_framework">A little framework</h2>
<p>Sometimes a page uses dozens and dozens of animations. In such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the <code>clearTimeout()</code> function. A possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them.<br />
  Here is a possible and minimalist example of such abstraction, which for this reason we named <code><em>MiniDaemon</em></code>.</p>
<div class="note">
  <strong>Note:</strong> For a more complex but still modular modular version of it (<code><em>Daemon</em></code>) see <a href="/en-US/docs/JavaScript/Timers/Daemons">JavaScript Daemons Management</a>. This more complex version is nothing but a big and scalable collection of methods for the <code><em>Daemon</em></code> constructor. But the <code><em>Daemon</em></code> constructor itself is nothing but a clone of <code><em>MiniDaemon</em></code> with an added support for <em>init</em> and <em>onstart</em> functions declarable during the instantiation of the <code><em>daemon</em></code>. <strong>So the <code><em>MiniDaemon</em></code> framework will remain the recommended way for simple animations</strong>, because <code><em>Daemon</em></code> without its collection of methods is essentially a clone of it.</div>
<p>The architecture of this constructor explicitly avoids the use of closures. <em>It also <strong>offers an alternative way to pass the <a href="/en-US/docs/JavaScript/Reference/Operators/this"><code>this</code></a> object to the callback function</strong> (see <a href="#The_.22this.22_problem" title="The 'this' problem">The "this" problem</a> for details).</em></p>
<h3 id="minidaemon.js">minidaemon.js</h3>
<pre class="brush:js">
/*\
|*|
|*|  MiniDaemon - Mozilla Developer Network - ver. 1.0 rev. 1
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
|*|&nbsp; https://developer.mozilla.org/User:fusionchess
|*|
|*|&nbsp; This framework is released under the GNU Public License, version 3 or later.
|*|&nbsp; http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
\*/
 
function MiniDaemon (oOwner, fTask, nRate, nLen) {
  if (!(this &amp;&amp; this instanceof MiniDaemon)) { return; }
  if (arguments.length &lt; 2) { throw new TypeError("MiniDaemon - not enough arguments"); }
  if (oOwner) { this.owner = oOwner; }
  this.task = fTask;
  if (isFinite(nRate) &amp;&amp; nRate &gt; 0) { this.rate = Math.floor(nRate); }
  if (nLen &gt; 0) { this.length = Math.floor(nLen); }
}
 
MiniDaemon.prototype.owner = null;
MiniDaemon.prototype.task = null;
MiniDaemon.prototype.rate = 100;
MiniDaemon.prototype.length = Infinity;
 
  /* These properties should be read-only */
 
MiniDaemon.prototype.SESSION = -1;
MiniDaemon.prototype.INDEX = 0;
MiniDaemon.prototype.PAUSED = true;
MiniDaemon.prototype.BACKW = true;
 
  /* Global methods */
 
MiniDaemon.forceCall = function (oDmn) {
  oDmn.INDEX += oDmn.BACKW ? -1 : 1;
  if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; }
  return true;
};
 
  /* Instances methods */
 
MiniDaemon.prototype.isAtEnd = function () {
  return this.BACKW ? isFinite(this.length) &amp;&amp; this.INDEX &lt; 1 : this.INDEX + 1 &gt; this.length;
};
 
MiniDaemon.prototype.synchronize = function () {
  if (this.PAUSED) { return; }
  clearInterval(this.SESSION);
  this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this);
};
 
MiniDaemon.prototype.pause = function () {
  clearInterval(this.SESSION);
  this.PAUSED = true;
};
 
MiniDaemon.prototype.start = function (bReverse) {
  var bBackw = Boolean(bReverse);
  if (this.BACKW === bBackw &amp;&amp; (this.isAtEnd() || !this.PAUSED)) { return; }
  this.BACKW = bBackw;
  this.PAUSED = false;
  this.synchronize();
};
</pre>
<div class="note">
  <strong>Note:</strong> This small framework utilises the <a href="#Callback_arguments">passage of arguments to the callback function</a>. If you want to work on it with browsers which natively do not support this feature, use the polyfill proposed here.</div>
<h3 id="Syntax">Syntax</h3>
<p><code>var myDaemon = new MiniDaemon(<em>thisObject</em>, <em>callback</em>[</code><code>, <em>rate</em></code><code>[, <em>length</em>]]);</code></p>
<h3 id="Description">Description</h3>
<p>Returns a JavaScript <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a> containing all informations needed by an animation (like the <a href="/en-US/docs/JavaScript/Reference/Operators/this"><code>this</code></a> object, the callback function, the length, the frame-rate).</p>
<h4 id="Parameters">Parameters</h4>
<dl>
  <dt>
    <code>thisObject</code></dt>
  <dd>
    The <a href="/en-US/docs/JavaScript/Reference/Operators/this"><code>this</code></a> object on which will be called the <em>callback</em> function. It can be an <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object"><code>object</code></a> or <code>null</code>.</dd>
  <dt>
    <code>callback</code></dt>
  <dd>
    The function which will be invoked repeatedly. <strong>It will be called with three parameters</strong>: <em>index</em> (the iterative index of each invocation), <em>length</em> (the number of total invocations assigned to the <em>daemon</em> - finite or <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>) and <em>backwards</em> (a boolean expressing whether the <em>index</em> is increasing or decreasing). It will be something like <em>callback</em>.call(<em>thisObject</em>, <em>index</em>, <em>length</em>, <em>backwards</em>). <strong>If the callback function returns a <code>false</code> value the <em>daemon</em> will be paused</strong>.</dd>
  <dt>
    <code>rate (optional)</code></dt>
  <dd>
    The time lapse (in number of milliseconds) between each invocation. The default value is 100.</dd>
  <dt>
    <code>length (optional)</code></dt>
  <dd>
    The total number of invocations. It can be a positive integer or <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>. The default value is <code>Infinity</code>.</dd>
</dl>
<h4 id="MiniDaemon_instances_properties"><code>MiniDaemon</code> instances properties</h4>
<dl>
  <dt>
    <code>myDaemon.owner</code></dt>
  <dd>
    The <a href="/en-US/docs/JavaScript/Reference/Operators/this"><code>this</code></a> object on which is executed the daemon (read/write). It can be an <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object"><code>object</code></a> or <code>null</code>.</dd>
  <dt>
    <code>myDaemon.task</code></dt>
  <dd>
    The function which will be repeatedly invoked (read/write). It will be called with three arguments: <em>index</em> (the iterative index of each invocation), <em>length</em> (the number of total invocations assigned to the daemon - finite or <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>) and backwards (a boolean expressing whether the <em>index</em> is decreasing or not) – see above. If the <code>myDaemon.task</code> function returns a <code>false</code> value the <em>daemon</em> will be paused.</dd>
  <dt>
    <code>myDaemon.rate</code></dt>
  <dd>
    The time lapse (in number of milliseconds) between each invocation (read/write).</dd>
  <dt>
    <code>myDaemon.length</code></dt>
  <dd>
    The total number of invocations. It can be a positive integer or <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a> (read/write).</dd>
</dl>
<h4 id="MiniDaemon_instances_methods"><code>MiniDaemon</code> instances methods</h4>
<dl>
  <dt>
    <code>myDaemon.isAtEnd()</code></dt>
  <dd>
    Returns a boolean expressing whether the <em>daemon</em> is at the start/end position or not.</dd>
  <dt>
    <code>myDaemon.synchronize()</code></dt>
  <dd>
    Synchronize the timer of a started daemon with the time of its invocation.</dd>
  <dt>
    <code>myDaemon.pause()</code></dt>
  <dd>
    Pauses the daemon.</dd>
  <dt>
    <code>myDaemon.start([<em>reverse</em>])</code></dt>
  <dd>
    Starts the daemon forward (<em>index</em> of each invocation increasing) or backwards (<em>index</em> decreasing).</dd>
</dl>
<h4 id="MiniDaemon_global_object_methods"><code>MiniDaemon</code> global object methods</h4>
<dl>
  <dt>
    <code>MiniDaemon.forceCall(<em>minidaemon</em>)</code></dt>
  <dd>
    Forces a single callback to the <code><em>minidaemon</em>.task</code> function regardless of the fact that the end has been reached or not. In any case the internal <code>INDEX</code> property will be increased/decreased (depending on the actual direction of the process).</dd>
</dl>
<h3 id="Example_usage">Example usage</h3>
<p>your HTML page:</p>
<pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;
&lt;title&gt;MiniDaemin Example - MDN&lt;/title&gt;
&lt;script type="text/javascript" src="minidaemon.js"&gt;&lt;/script&gt;
&lt;style type="text/css"&gt;
#sample_div {
  visibility: hidden;
}
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;p&gt;&lt;input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" /&gt; &lt;input type="button" onclick="fadeInOut.start(true);" value="fade out"&gt; &lt;input type="button" onclick="fadeInOut.pause();" value="pause" /&gt;&lt;/p&gt;
&lt;div id="sample_div"&gt;Some text here&lt;/div&gt;

&lt;script type="text/javascript"&gt;
function opacity (nIndex, nLength, bBackwards) {
  this.style.opacity = nIndex / nLength;
  if (bBackwards ? nIndex === 0 : nIndex === 1) {
    this.style.visibility = bBackwards ? "hidden" : "visible";
  }
}

var fadeInOut = new MiniDaemon(document.getElementById("sample_div"), opacity, 300, 8);
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p><a href="/files/3995/minidaemon_example.html" title="MiniDaemon Example">View this example in action</a></p>
<h2 id="Notes">Notes</h2>
<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 <a href="/en-US/docs/DOM/window.clearInterval"><code>window.clearInterval()</code></a>.</p>
<p>If you wish to have your function called <em>once</em> after the specified delay, use <a href="/en-US/docs/DOM/window.setTimeout"><code>window.setTimeout()</code></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 <code><a href="/en-US/docs/DOM/window.setTimeout">window.setTimeout</a></code>. For example, if using <code>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>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<div>
  {{CompatibilityTable}}</div>
<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>
      <tr>
        <td>Supports parameters for callback*1</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>10.0</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>{{CompatUnknown}}</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>
      <tr>
        <td>Supports parameters for callback*1</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
        <td>{{CompatUnknown}}</td>
      </tr>
    </tbody>
  </table>
</div>
<p>*1 Whether it supports the optional parameters when in its first form or not.</p>
<h2 id="Specification" name="Specification">Specification</h2>
<p>{{DOM0}}</p>
<h2 id="See_also" name="See_also">See also</h2>
<ul>
  <li><a href="/en-US/docs/JavaScript/Timers">JavaScript timers</a></li>
  <li>{{domxref("window.setTimeout")}}</li>
  <li>{{domxref("window.clearTimeout")}}</li>
  <li>{{domxref("window.clearInterval")}}</li>
  <li>{{domxref("window.requestAnimationFrame")}}</li>
  <li><a href="/en-US/docs/JavaScript/Timers/Daemons"><em>Daemons</em> management</a></li>
</ul>
Revert to this revision