Browser - setTimeOut

Browser

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 (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);
});
  • The button to start the demo
<button id="startButton">Start Demo</button>
  • Output:

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.

Syntax

1)

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





Recommended Pages
Browser
Browser - Web API - setInterval

setInterval permits to execute a function at regulier interval. setTimeout Increment and log the variable i every 3 seconds. The intervalFunctionId is called a timerId. setTimeout. It is used in...
Puppeteer Architecture
Headless browser - Puppeteer

Puppeteer is a Node library that provides a high-level API over Chrome or Chromium (ie headless chrome) Puppeteer communicate with the browser via the DevTools Protocol API The Puppeteer API is hierarchical...
Javascript - Debounce Function

A debounce is a function that: will wrap a callback function willnot let the callback function execute for each event will let the callback function execute only when a certain amount of time...
Javascript - Thread Wait ?

JavaScript is a single-thread event-based model. Therefore, you don't want and can't stop the execution of code. May be with ? API The setTimeOut is wrapper around code that create a job to execute...



Share this page:
Follow us:
Task Runner