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) runs handler once after at least timeout milliseconds.
  • setInterval(handler, timeout, ...args) runs handler repeatedly every timeout milliseconds.
  • clearTimeout(id) and clearInterval(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);

Documentation#