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);
});
- 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
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