DOM:window.setTimeout
From MDC
Contents |
[edit] Summary
Executes a code snippet or a function after specified delay.
[edit] Syntax
timeoutID = window.setTimeout(func, delay, [param1, param2, ...]); timeoutID = window.setTimeout(code, delay);
where
-
timeoutIDis the ID of the timeout, which can be used with window.clearTimeout. -
funcis the function you want to execute afterdelaymilliseconds. -
codein the alternate syntax, is a string of code you want to execute afterdelaymilliseconds. (not recommended) -
delayis the number of milliseconds (thousandths of a second) that the function call should be delayed by.
Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer.
[edit] Compatibility
Introduced with JavaScript 1.0, Netscape 2.0. Passing a Function object reference was introduced with JavaScript 1.2, Netscape 4.0; supported by the MSHTML DOM since version 5.0.
[edit] Examples
window.setTimeout('window.parent.generateOutput()', 1000);
function generateOutput(aConcise) {
if(aConcise)
parent.generateConciseOutput();
else
parent.generateOutput();
}
window.setTimeout(generateOutput, 1000, true);
<html>
<head>
<title>setTimeout example</title>
<script type="text/javascript">
function delayedAlert()
{
timeoutID = window.setTimeout(slowAlert, 2000);
}
function slowAlert()
{
alert("That was really slow!");
}
function clearAlert()
{
window.clearTimeout(timeoutID);
}
</script>
</head>
<body>
<button onclick="delayedAlert();"
>show an alert box after 2 seconds</button><br>
<button onclick="clearAlert();">Cancel</button>
</body>
</html>
See also clearTimeout() example.
[edit] Notes
You can cancel the timeout using window.clearTimeout().
If you wish to have your function called repeatedly (i.e. every N milliseconds), consider using window.setInterval().
[edit] The 'this' problem
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. This issue is explained in more detail in the JavaScript reference.
[edit] Specification
DOM Level 0. Not part of any standard.