Table of Contents

How to use the setTimeOut javascript function (in the Browser)?

About

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

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

Example

In this example, we will print 4 messages at different intervals.

// print a message
function printMessage(id, interval) {
    console.log(`The message (${id}) was printed with an interval of ${interval} seconds`);
}

// print a message at a certain interval with timeout
function printMessageIdAfterXSec(id, interval) {
    window.setTimeout(function() { printMessage(id, interval) },interval*1000);
}

// when the button is clicked, 4 messages are asked at interval
document.getElementById("startButton").addEventListener("click", function () {
   printMessageIdAfterXSec("message 1", 2);
   printMessageIdAfterXSec("message 2", 1);
   printMessageIdAfterXSec("message 3", 0);
   printMessageIdAfterXSec("message 4", 3);
});
<button id="startButton">Start Demo</button>

Characteristic

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

setTimeout:

Syntax

1)

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

where: