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

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.

Inactive tabs

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):

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:

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.

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

Syntax

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

Notes

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.

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.

Learn the best of web development

Get the latest and greatest from MDN delivered straight to your inbox.

E-mail

I'm okay with Mozilla handling my info as explained in this Privacy Policy.

Thanks! Please check your inbox to confirm your subscription.

If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.

Why does MDN look different?

MDN is changing to focus just on documenting web technologies. All the same great content is still here; we’re just changing some visual elements and navigation, to help you more quickly find the web technology docs you’re looking for.

But don’t worry, MDN and Mozilla are still together! In fact, we're updating MDN’s look to reflect Mozilla's new logo and colors.