setTimeout:
function sayHi(name) {
console.log(`Hi ${name}`);
}
const timerId = setTimeout(sayHi, 100, "John");
// clearing a timeOut
clearTimeout(timerId);
the delay:
function sayHi() {
console.log(`Hi John`);
}
const timerId = setTimeout(sayHi, 100);
// clearing a timeOut
clearTimeout(timerId);
execution:
execution:
0ms delay:
function foo() {
console.log("foo has been called");
}
setTimeout(foo, 0);
console.log("After setTimeout");
// "After setTimeout"
// "foo has been called"
Nesting setTimeout instead of setInterval:
/** instead of:
let timerId = setInterval(
() => alert('tick'), 2000);
*/
let timerId = setTimeout(function tick() {
alert('tick');
timerId = setTimeout(tick, 2000);
}, 2000);
// example 2
let start = Date.now();
let times = [];
setTimeout(function run() {
// remember delay from the previous call
times.push(Date.now() - start);
// show the delays after 100ms
if (start + 100 < Date.now()) alert(times);
else setTimeout(run); // else re-schedule
});