Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1000757 of WindowTimers.setTimeout()

  • Revision slug: Web/API/WindowTimers/setTimeout
  • Revision title: WindowTimers.setTimeout()
  • Revision id: 1000757
  • Created:
  • Creator: Victor_Homyakov
  • Is current revision? No
  • Comment

Revision Content

{{APIRef("HTML DOM")}}

Calls a function or executes a code snippet after a specified delay.

Syntax

var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code, [delay]);

where

  • timeoutID is the numerical ID of the timeout, which can be used later with {{domxref("window.clearTimeout()")}}.
  • func is the function you want to execute after delay milliseconds.
  • code in the alternate syntax is a string of code you want to execute after delay milliseconds (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 function call should be delayed by. If omitted, it defaults to 0. The actual delay may be longer; see {{anch("Notes")}} below.
  • param1, param2, and so forth are additional parameters which are passed through to the function specified by func.

Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer 9 and below. If you want to enable this functionality on that browser, you must use a polyfill (see the Callback arguments section).

Example

The following example sets up two simple buttons in a web page and hooks them to the setTimeout() and clearTimeout() routines. Pressing the first button will set a timeout which calls an alert dialog after two seconds and stores the timeout id for use by clearTimeout(). You may optionally cancel this timeout by pressing on the second button.

HTML Content

<p>Live Example</p>
<button onclick="delayedAlert();">Show an alert box after two seconds</button>
<p></p>
<button onclick="clearAlert();">Cancel alert before it happens</button>

JavaScript Content

var timeoutID;

function delayedAlert() {
  timeoutID = window.setTimeout(slowAlert, 2000);
}

function slowAlert() {
  alert("That was really slow!");
}

function clearAlert() {
  window.clearTimeout(timeoutID);
}

{{EmbedLiveSample('Example')}}

See also clearTimeout() example.

Polyfill

If you need to pass one or more arguments to your callback function, but need it to work in browsers which don't support sending additional parameters using either setTimeout() or setInterval() (e.g. Internet Explorer 9 and below), you can include this polyfill which enables the HTML5 standard parameter-passing functionality. Just add this code to the top of your script:

/*\
|*|
|*|  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/DOM/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);
|*|
\*/

(function() {
  setTimeout(function(arg1) {
    if (arg1 === 'test') {
      // feature test is passed, no need for polyfill
      return;
    }
    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);
    };
  }, 0, 'test');

  var interval = setInterval(function(arg1) {
    clearInterval(interval);
    if (arg1 === 'test') {
      // feature test is passed, no need for polyfill
      return;
    }
    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);
    };
  }, 0, 'test');
}())

IE only fix

If you want a completely unobtrusive hack for every other mobile or desktop browser, including IE 9 and below, you can either use JavaScript conditional comments:

/*@cc_on
  // conditional IE < 9 only fix
  @if (@_jscript_version <= 9)
  (function(f){
     window.setTimeout=f(window.setTimeout);
     window.setInterval=f(window.setInterval);
  })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}});
  @end
@*/

Or go for a very clean approach based on the IE HTML conditional feature:

<!--[if lte IE 9]><script>
(function(f){
window.setTimeout=f(window.setTimeout);
window.setInterval=f(window.setInterval);
})(function(f){return function(c,t){
var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}
});
</script><![endif]-->

Workarounds

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

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

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

setTimeout(function(arg1){}.bind(undefined, 10), 1000);

The "this" problem

When you pass a method to setTimeout() (or any other function, for that matter), it will be invoked with a this value that may differ from your expectation. This issue is explained in detail in the JavaScript reference.

Explanation

Code executed by setTimeout() 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:

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: These 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 polyfills also. See the Callback arguments paragraph.

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

There are not native solutions ad hoc to this problem.

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.

Example using bind:

myArray = ["zero", "one", "two"];
myBoundMethod = (function (sProperty) {
    console.log(arguments.length > 0 ? this[sProperty] : this);
}).bind(myArray);

myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function
myBoundMethod(1); // prints "one"
setTimeout(myBoundMethod, 1000); // still prints "zero,one,two" after 1 second because of the binding
setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds

Notes

You can cancel the timeout using window.clearTimeout(). If you wish to have your function called repeatedly (e.g., every N milliseconds), consider using window.setInterval().

It's important to note that the function or code snippet cannot be executed until the thread that called setTimeout() has terminated.

Passing string literals

Passing a string instead of a function to setTimeout() suffers from the same hazards as using eval.

// Recommended
window.setTimeout(function() {
    alert("Hello World!");
}, 500);

// Not recommended
window.setTimeout("alert('Hello World!');", 500);

A string passed to setTimeout is evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

Reasons for delays longer than specified

Nested timeouts forced to >=4ms

Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5.

In fact, 4 ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to {{geckoRelease("5.0")}}, the minimum timeout value for nested timeouts was 10 ms.

To implement a 0 ms timeout in a modern browser, you can use {{domxref("window.postMessage()")}} as described here.

Timeouts in inactive tabs clamped to >=1000ms

To reduce the load (and associated battery usage) from background tabs, timeouts are often clamped to firing no more often than once per second (1000 ms) in inactive tabs.

Firefox implements this behavior since version 5 (see {{bug(633421)}}, the 1000ms constant can be tweaked through the dom.min_background_timeout_value preference). Chrome implements this behavior since version 11 (crbug.com/66078).

Late timeouts

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.

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

Maximum delay value

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.

Specifications

Specification Status Comment
{{SpecName("HTML WHATWG", "webappapis.html#dom-windowtimers-settimeout", "WindowTimers.setTimeout()")}} {{Spec2("HTML WHATWG")}} Initial definition (DOM Level 0)

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.

See also

Revision Source

<div>{{APIRef("HTML DOM")}}</div>

<p>Calls a function or executes a code snippet after a specified delay.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox">
<em>var timeoutID</em> = window.setTimeout(<em>func</em>, [<em>delay</em>, <em>param1</em>, <em>param2</em>, ...]);
<em>var timeoutID</em> = window.setTimeout(<em>code</em>, [<em>delay</em>]);
</pre>

<p>where</p>

<ul>
 <li><code>timeoutID</code> is the <em>numerical</em> ID of the timeout, which can be used later with {{domxref("window.clearTimeout()")}}.</li>
 <li><code>func</code> is the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">function</a> you want to execute after <code>delay</code> milliseconds.</li>
 <li><code>code</code> in the alternate syntax is a string of code you want to execute after <code>delay</code> milliseconds (using this syntax is <strong>not recommended</strong> for the same reasons as using <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don't_use_eval_needlessly!">eval()</a>)</li>
 <li><code>delay</code> is the number of milliseconds (thousandths of a second) that the function call should be delayed by. If omitted, it defaults to 0. The actual delay may be longer; see {{anch("Notes")}} below.</li>
 <li><code>param1</code>, <code>param2</code>, and so forth are additional parameters which are passed through to the function specified by <code>func</code>.</li>
</ul>

<p>Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer 9 and below. If you want to enable this functionality on that browser, you must use a polyfill (see the <a href="#Callback_arguments">Callback arguments</a> section).</p>

<h2 id="Example">Example</h2>

<p>The following example sets up two simple buttons in a web page and hooks them to the <code>setTimeout()</code> and <code>clearTimeout()</code> routines. Pressing the first button will set a timeout which calls an alert dialog after two seconds and stores the timeout id for use by <code>clearTimeout()</code>. You may optionally cancel this timeout by pressing on the second button.</p>

<h3 id="HTML_Content">HTML Content</h3>

<pre class="brush: html">
&lt;p&gt;Live Example&lt;/p&gt;
&lt;button onclick="delayedAlert();"&gt;Show an alert box after two seconds&lt;/button&gt;
&lt;p&gt;&lt;/p&gt;
&lt;button onclick="clearAlert();"&gt;Cancel alert before it happens&lt;/button&gt;
</pre>

<h3 id="JavaScript_Content">JavaScript Content</h3>

<pre class="brush: js">
var timeoutID;

function delayedAlert() {
  timeoutID = window.setTimeout(slowAlert, 2000);
}

function slowAlert() {
  alert("That was really slow!");
}

function clearAlert() {
  window.clearTimeout(timeoutID);
}
</pre>

<p>{{EmbedLiveSample('Example')}}</p>

<p>See also <a href="/en-US/docs/Web/API/WindowTimers/clearTimeout#Example"><code>clearTimeout()</code> example</a>.</p>

<h2 id="Callback_arguments">Polyfill</h2>

<p>If you need to pass one or more arguments to your callback function, but need it to work in browsers&nbsp;which don't support sending additional parameters using either <code>setTimeout()</code> or <code>setInterval() (e.g. </code>Internet Explorer 9 and below<code>)</code>, you can include this&nbsp;polyfill which enables the HTML5 standard parameter-passing functionality. Just add this code to the top of your script:</p>

<pre class="brush: js">
/*\
|*|
|*|  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/DOM/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);
|*|
\*/

(function() {
&nbsp; setTimeout(function(arg1) {
&nbsp; &nbsp; if (arg1 === 'test') {
&nbsp; &nbsp; &nbsp; // feature test is passed, no need for polyfill
&nbsp; &nbsp; &nbsp; return;
&nbsp; &nbsp; }
&nbsp; &nbsp; var __nativeST__ = window.setTimeout;
&nbsp; &nbsp; window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
&nbsp; &nbsp; &nbsp; var aArgs = Array.prototype.slice.call(arguments, 2);
&nbsp; &nbsp; &nbsp; return __nativeST__(vCallback instanceof Function ? function() {
&nbsp; &nbsp; &nbsp; &nbsp; vCallback.apply(null, aArgs);
&nbsp; &nbsp; &nbsp; } : vCallback, nDelay);
&nbsp; &nbsp; };
&nbsp; }, 0, 'test');

&nbsp; var interval = setInterval(function(arg1) {
&nbsp; &nbsp; clearInterval(interval);
&nbsp; &nbsp; if (arg1 === 'test') {
&nbsp; &nbsp; &nbsp; // feature test is passed, no need for polyfill
&nbsp; &nbsp; &nbsp; return;
&nbsp; &nbsp; }
&nbsp; &nbsp; var __nativeSI__ = window.setInterval;
&nbsp; &nbsp; window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
&nbsp; &nbsp; &nbsp; var aArgs = Array.prototype.slice.call(arguments, 2);
&nbsp; &nbsp; &nbsp; return __nativeSI__(vCallback instanceof Function ? function() {
&nbsp; &nbsp; &nbsp; &nbsp; vCallback.apply(null, aArgs);
&nbsp; &nbsp; &nbsp; } : vCallback, nDelay);
&nbsp; &nbsp; };
&nbsp; }, 0, 'test');
}())
</pre>

<h2 id="IE_only_fix">IE only fix</h2>

<p>If you want a completely unobtrusive hack for every other mobile or desktop browser, including IE 9 and below, you can either use JavaScript conditional comments:</p>

<pre class="brush: js">
/*@cc_on
  // conditional IE &lt; 9 only fix
  @if (@_jscript_version &lt;= 9)
  (function(f){
     window.setTimeout=f(window.setTimeout);
     window.setInterval=f(window.setInterval);
  })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}});
  @end
@*/
</pre>

<p>Or go for a very clean approach based on the IE HTML conditional feature:</p>

<pre class="brush: html">
&lt;!--[if lte IE 9]&gt;&lt;script&gt;
(function(f){
window.setTimeout=f(window.setTimeout);
window.setInterval=f(window.setInterval);
})(function(f){return function(c,t){
var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}
});
&lt;/script&gt;&lt;![endif]--&gt;
</pre>

<h2>Workarounds</h2>

<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 = setTimeout(function() { myFunc("one", "two", "three"); }, 1000);
</pre>

<p>Yet another possibility is to use <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">function's <code>bind</code></a>. Example:</p>

<pre class="brush: js">
setTimeout(function(arg1){}.bind(undefined, 10), 1000);
</pre>

<h2 id="The_this_problem">The "<code>this</code>" problem</h2>

<p>When you pass a method to <code>setTimeout()</code> (or any other function, for that matter), it will be invoked with a&nbsp;<code>this</code> value that may differ from your expectation. This issue is explained in detail in the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this#As_an_object_method">JavaScript reference</a>.</p>

<h3 id="Explanation">Explanation</h3>

<p>Code executed by <code>setTimeout()</code> is run in a separate execution context to the function from which it was called. As a consequence, the <code>this</code> 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:</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/Web/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> These 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 polyfills also. See the <a href="#Callback_arguments">Callback arguments</a> paragraph.</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>There are not native solutions <em>ad hoc</em> to this problem.</p>

<div class="note"><strong>Note:</strong> JavaScript 1.8.5 introduces the <code><a href="/en-US/docs/Web/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>

<p>Example using bind:</p>

<pre class="brush: js">
myArray = ["zero", "one", "two"];
myBoundMethod = (function (sProperty) {
    console.log(arguments.length &gt; 0 ? this[sProperty] : this);
}).bind(myArray);

myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function
myBoundMethod(1); // prints "one"
setTimeout(myBoundMethod, 1000); // still prints "zero,one,two" after 1 second because of the binding
setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds
</pre>

<h2 id="Notes">Notes</h2>

<p>You can cancel the timeout using <code><a href="/en-US/docs/Web/API/WindowTimers/clearTimeout">window.clearTimeout()</a></code>. If you wish to have your function called repeatedly (e.g., every N milliseconds), consider using <code><a href="/en-US/docs/Web/API/WindowTimers/setInterval">window.setInterval()</a></code>.</p>

<p>It's important to note that the function or code snippet cannot be executed until the thread that called <code>setTimeout()</code> has terminated.</p>

<h3 id="Passing_string_literals">Passing string literals</h3>

<p>Passing a string instead of a function to <code>setTimeout()</code> suffers from the same hazards as using <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/eval#Don.27t_use_eval.21">eval</a>. </code></p>

<pre class="brush: js">
// Recommended
window.setTimeout(function() {
    alert("Hello World!");
}, 500);

// Not recommended
window.setTimeout("alert('Hello World!');", 500);
</pre>

<p>A string passed to <code>setTimeout</code> is evaluated in the global context, so local symbols in the context where <code>setTimeout()</code> was called will not be available when the string is evaluated as code.</p>

<h3 id="Reasons_for_delays_longer_than_specified">Reasons for delays longer than specified</h3>

<h4 id="Nested_timeouts_forced_to_&gt;4ms">Nested timeouts forced to &gt;=4ms</h4>

<p><a class="external" href="https://code.google.com/p/chromium/issues/detail?id=792#c10">Historically</a> browsers implement <code>setTimeout()</code> "clamping": successive <code>setTimeout()</code> calls with <code>delay</code> smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, <code>DOM_MIN_TIMEOUT_VALUE</code>, is 4 ms (stored in a preference in Firefox: <code>dom.min_timeout_value</code>), with a <code>DOM_CLAMP_TIMEOUT_NESTING_LEVEL</code> of 5.</p>

<p>In fact, 4 ms is <a class="external" href="https://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers">specified by the HTML5 spec</a> and is consistent across browsers released in 2010 and onward. Prior to {{geckoRelease("5.0")}}, the minimum timeout value for nested timeouts was 10 ms.</p>

<p>To implement a 0 ms timeout in a modern browser, you can use {{domxref("window.postMessage()")}} as <a class="external" href="https://dbaron.org/log/20100309-faster-timeouts">described here</a>.</p>

<h4 id="Timeouts_in_inactive_tabs_clamped_to_&gt;1000ms">Timeouts in inactive tabs clamped to &gt;=1000ms</h4>

<p>To reduce the load (and associated battery usage) from background tabs, timeouts are often clamped to firing no more often than once per second (1000 ms) in inactive tabs.</p>

<p>Firefox implements this behavior since version 5 (see {{bug(633421)}}, the 1000ms constant can be tweaked through the <span class="comment-copy"><code>dom.min_background_timeout_value</code> preference).</span> Chrome implements this behavior since version 11 (<a class="external" href="https://crbug.com/66078">crbug.com/66078</a>).</p>

<h4 id="Late_timeouts">Late timeouts</h4>

<p>In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.</p>

<p>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 passed.</p>

<h3 id="Maximum_delay_value">Maximum delay value</h3>

<p>Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th>Specification</th>
   <th>Status</th>
   <th>Comment</th>
  </tr>
  <tr>
   <td>{{SpecName("HTML WHATWG", "webappapis.html#dom-windowtimers-settimeout", "WindowTimers.setTimeout()")}}</td>
   <td>{{Spec2("HTML WHATWG")}}</td>
   <td>Initial definition (DOM Level 0)</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<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>
  <tr>
   <td>Supports parameters for callback<sup>[1]</sup></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<sup>[1]</sup></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="See_also">See also</h2>

<ul>
 <li><a href="/en-US/Add-ons/Code_snippets/Timers">JavaScript timers</a></li>
 <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Timer.jsm">Timer.jsm</a></li>
 <li>{{domxref("WindowTimers.setInterval")}}</li>
 <li>{{domxref("window.requestAnimationFrame")}}</li>
 <li><a href="/en-US/Add-ons/Code_snippets/Timers/Daemons"><em>Daemons</em> management</a></li>
</ul>
Revert to this revision