Browser - setTimeOut

> (World Wide) Web - (W3|WWW) > Web - Browser

1 - About

setTimeOut is a web api (browser function that wraps code in a job and execute it later.

The execution of the main thread (of the code) therefore does not stop.

Advertising

3 - Characteristic

setTimeout put the function in the window (global scope).

setTimeout:

  • does not hold up execution, it executes the next line of the function immediately after the timeout is SET, not after the timeout expires.
  • does execute the code with eval. It means that the value of the called function parameters may have changed between the timeout and the execution of the code.

4 - Syntax

WindowOrWorkerGlobalScope/setTimeout

var timerId = setTimeout(function[, delay, arg1, arg2, ...]);
var timerId = setTimeout(function[, delay]);
var timerId = setTimeout(code[, delay]);

where:

  • function is a function
  • code is a string of code (that is evaluated).
  • delay is the time, in milliseconds.
  • arg1, …, argN are arguments passed to the function
  • timerId is the id of the job (timer) setInterval() uses the same timeId pool that can be used in the clearTimeout function
Advertising

5 - Example

var countDelayedMessage = 0;
var countMessage = 0;
 
function printMessage(countMessage) {
    countDelayedMessage++;
    console.log("Count="+countDelayedMessage + ", countMessage="+countMessage);
}
 
/**
 * Add a message after a number of second
 * @param s A string
 * @param sec The number of second to wait
 */
function printMessageAfter() {
    countMessage++;
    window.setTimeout(function() { printMessage(countMessage) },countMessage*1000);
}
 
var button = document.getElementById("startButton");
button.addEventListener("click",
    function () {
        printMessageAfter();
        printMessageAfter();
        printMessageAfter();
        printMessageAfter();
}, false);
<button id="startButton">Start Demo</button>

countMessage is passed in the invocation of the function printMessage but the value uses is the the value of the call but of the execution (and therefore it will be always 4)