Browser - setTimeOut

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.

3 - Characteristic

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


  • 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


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


  • 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) <note warning>setInterval() uses the same timeId pool</note> that can be used in the clearTimeout function

5 - Example

var countDelayedMessage = 0;
var countMessage = 0;

function printMessage(countMessage) {
    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() {
    window.setTimeout(function() { printMessage(countMessage) },countMessage*1000);

var button = document.getElementById("startButton");
    function () {
}, 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)

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap