Glossary / Timers

Timers

Timers schedule callbacks to become eligible after a delay; they do not guarantee execution at an exact time. setTimeout schedules one callback, setInterval schedules repeated callbacks, and matching clear functions cancel pending registrations. Browsers and Node.js implement timers as host APIs integrated with their event loops, so timing, throttling, and ordering details can vary.

Delay is a lower bound, not a deadline

A timer callback cannot run while the current synchronous job occupies the event loop. Once eligible, it still waits for other queued work. Browsers clamp nested timers and throttle background tabs; delays are converted/coerced and have implementation limits. A setTimeout(fn, 0) callback is asynchronous and usually runs after current microtasks, but it is not a precise “next tick.”

setInterval schedules according to host timing and callbacks may run later than nominally requested when work blocks. If callback work takes longer than the interval, behavior can cause overlap/backlog or timing drift depending on the host. For polling, a recursive timeout scheduled after completion avoids concurrent overlapping requests:

async function poll() {
  try { await refresh(); }
  finally { setTimeout(poll, 1000); }
}

This example needs a cancellation/lifecycle mechanism in real code. For visual animation, prefer requestAnimationFrame; for elapsed time, compare timestamps from a monotonic clock rather than counting timer callbacks.

Interview questions

  1. Does a timer delay guarantee callback time? No; it only makes it eligible after a minimum delay.
  2. Why is a zero-delay timeout not immediate? Current code and microtasks must finish, then the host schedules the task.
  3. What timer for animation? requestAnimationFrame.
  4. What is a safer polling pattern? Schedule the next timeout after current async work settles, and support cancellation.

References