Glossary / setInterval

setInterval

setInterval(callback, delay) schedules a callback repeatedly with an intended interval. Like other timers, it does not guarantee exact timing: the callback waits for the event loop, can be throttled in background contexts, and may drift relative to wall-clock time. clearInterval(id) cancels future scheduled firings but cannot interrupt a callback already running.

Overlap and drift

If an interval callback starts asynchronous work and that work lasts longer than the interval, multiple operations may overlap. This can create duplicate requests, out-of-order results, or growing resource pressure. For polling where overlap is undesirable, schedule the next timeout after the current operation completes:

let stopped = false;
async function poll() {
  try { await refresh(); }
  finally { if (!stopped) setTimeout(poll, 1000); }
}

Production code should clear/cancel on disposal, handle errors, and abort in-flight work. If updates need fixed-rate cadence, compute the next deadline from a monotonic timestamp and account for missed ticks rather than assuming callbacks arrive exactly on time. Timers are not appropriate for frame-by-frame animation; use requestAnimationFrame. They are not a reliable clock for counting elapsed time because throttling can skip or delay callbacks.

Interview questions

  1. What can happen if async work exceeds the interval? Work can overlap or accumulate, depending on scheduling and callback design.
  2. How avoid overlapping polls? Use recursive setTimeout after completion or a guarded single-flight operation.
  3. Can clearInterval stop a running callback? No.
  4. Should intervals drive animation? Usually no; use requestAnimationFrame and its timestamp.

References