timers
The timer functions schedule work to run after a delay or on a repeating interval. They are globals — available without importing anything.
setTimeout(handler, timeout, ...args)runshandleronce after at leasttimeoutmilliseconds.setInterval(handler, timeout, ...args)runshandlerrepeatedly everytimeoutmilliseconds.clearTimeout(id)andclearInterval(id)cancel a scheduled timer.
Both functions return a numeric id that can be passed to either clear function. Extra arguments are forwarded to the handler.
Usage#
const id = setTimeout(
(name) => console.log(`Hello, ${name}!`),
1000,
"world",
);
setTimeout(() => clearTimeout(id), 500); // cancels before it fires
let ticks = 0;
const interval = setInterval(() => {
ticks++;
console.log("tick", ticks);
if (ticks >= 3) clearInterval(interval);
}, 500);