6.3 Timers

The setTimeout() and setInterval() methods allow authors to schedule timer-based callbacks.

[NoInterfaceObject]
interface WindowTimers {
  long setTimeout(Function handler, optional long timeout, any... arguments);
  long setTimeout(DOMString handler, optional long timeout, any... arguments);
  void clearTimeout(long handle);
  long setInterval(Function handler, optional long timeout, any... arguments);
  long setInterval(DOMString handler, optional long timeout, any... arguments);
  void clearInterval(long handle);
};
Window implements WindowTimers;
handle = window . setTimeout( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

handle = window . setTimeout( code [, timeout ] )

Schedules a timeout to compile and run code after timeout milliseconds.

window . clearTimeout( handle )

Cancels the timeout set with setTimeout() identified by handle.

handle = window . setInterval( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.

handle = window . setInterval( code [, timeout ] )

Schedules a timeout to compile and run code every timeout milliseconds.

window . clearInterval( handle )

Cancels the timeout set with setInterval() identified by handle.

This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

The WindowTimers interface adds to the Window interface and the WorkerUtils interface (part of Web Workers). [WEBWORKERS]

Each object that implements the WindowTimers interface has a list of active timers. Each entry in this lists is identified by a number, which must be unique within the list for the lifetime of the object that implements the WindowTimers interface.


The setTimeout() method must run the following steps:

  1. Let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call in the list of active timers.

  2. Add an entry to the list of active timers for handle.

  3. Get the timed task handle in the list of active timers, and let task be the result. This algorithm uses the first argument to the method (handler) and, if there are any, the third and subsequent arguments to the method (arguments), to establish precisely what task does.

  4. Let timeout be the second argument to the method, or zero if the argument was omitted.

  5. If the currently running task is a task that was created by the setTimeout() method, and timeout is less than 4, then increase timeout to 4.

  6. Return handle, and then continue running this algorithm asynchronously.

  7. If the method context is a Window object, wait until the Document associated with the method context has been fully active for a further timeout milliseconds (not necessarily consecutively).

    Otherwise, if the method context is a WorkerUtils object, wait until timeout milliseconds have passed with the worker not suspended (not necessarily consecutively).

    Otherwise, act as described in the specification that defines that the WindowTimers interface is implemented by some other object.

  8. Wait until any invocations of this algorithm that had the same method context, that started before this one, and whose timeout is equal to or less than this one's, have completed.

    Argument conversion as defined by Web IDL (for example, invoking toString() methods on objects passed as the first argument) happens in the algorithms defined in Web IDL, before this algorithm is invoked.

    So for example, the following rather silly code will result in the log containing "ONE TWO ":

    var log = '';
    function logger(s) { log += s + ' '; }
    
    setTimeout({ toString: function () {
      setTimeout("logger('ONE')", 100);
      return "logger('TWO')";
    } }, 100);
  9. Optionally, wait a further user-agent defined length of time.

    This is intended to allow user agents to pad timeouts as needed to optimise the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

  10. Queue the task task.

    Once the task has been processed, it is safe to remove the entry for handle from the list of active timers (there is no way for the entry's existence to be detected past this point, so it does not technically matter one way or the other).


The setInterval() method must run the following steps:

  1. Let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call in the list of active timers.

  2. Add an entry to the list of active timers for handle.

  3. Get the timed task handle in the list of active timers, and let task be the result. This algorithm uses the first argument to the method (handler) and, if there are any, the third and subsequent arguments to the method (arguments), to establish precisely what task does.

  4. Let timeout be the second argument to the method, or zero if the argument was omitted.

  5. If timeout is less than 4, then increase timeout to 4.

  6. Return handle, and then continue running this algorithm asynchronously.

  7. Wait: If the method context is a Window object, wait until the Document associated with the method context has been fully active for a further interval milliseconds (not necessarily consecutively).

    Otherwise, if the method context is a WorkerUtils object, wait until interval milliseconds have passed with the worker not suspended (not necessarily consecutively).

    Otherwise, act as described in the specification that defines that the WindowTimers interface is implemented by some other object.

  8. Optionally, wait a further user-agent defined length of time.

    This is intended to allow user agents to pad timeouts as needed to optimise the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

  9. Queue the task task.

  10. Return to the step labeled wait.


The clearTimeout() and clearInterval() methods must clear the entry identified as handle from the list of active timers of the WindowTimers object on which the method was invoked, where handle is the argument passed to the method, if any. (If handle does not identify an entry in the list of active timers of the WindowTimers object on which the method was invoked, the method does nothing.)


The method context, when referenced by the algorithms in this section, is the object on which the method for which the algorithm is running is implemented (a Window or WorkerUtils object).

When the above methods are invoked and try to get the timed task handle in list list, they must run the following steps:

  1. If the first argument to the invoked method is a Function, then return a task that runs the following substeps, and then abort these steps:

    1. If the entry for handle in list has been cleared, then abort this task's substeps.

    2. Call the Function. Use the third and subsequent arguments to the invoked method (if any) as the arguments for invoking the Function. Use the undefined value as the thisArg for invoking the Function. [ECMA262]

      Setting thisArg to undefined means that the function code will be executed with the this keyword bound to the WindowProxy or the WorkerGlobalScope object, as if the code was running in the global scope.

    Otherwise, continue with the remaining steps.

  2. Let script source be the first argument to the method.

  3. Let script language be JavaScript.

  4. If the method context is a Window object, let global object be the method context, let browsing context be the browsing context with which global object is associated, let document and referrer source be the Document associated with global object, let character encoding be the character encoding of the Document associated with global object (this is a reference, not a copy), and let base URL be the base URL of the Document associated with global object (this is a reference, not a copy).

    Otherwise, if the method context is a WorkerUtils object, let global object, browsing context, document, referrer source, character encoding, and base URL be the script's global object, script's browsing context, script's document, script's referrer source, script's URL character encoding, and script's base URL (respectively) of the script that the run a worker algorithm created when it created the method context.

    Otherwise, act as described in the specification that defines that the WindowTimers interface is implemented by some other object.

  5. Return a task that checks if the entry for handle in list has been cleared, and if it has not, creates a script using script source as the script source, the URL where script source can be found, scripting language as the scripting language, global object as the global object, browsing context as the browsing context, document as the document, referrer source as the referrer source, character encoding as the URL character encoding, and base URL as the base URL.


The task source for these tasks is the timer task source.