CodeOath
← All posts
JavaScript75 min total · 15 parts

JavaScript Core Concepts: Scope, Closures, `this`, and the Event Loop

Contents — Part 14 of 15: setTimeout, setInterval, and Their Gotchas
Part 14 of 15 · ~1 min

setTimeout, setInterval, and Their Gotchas

setTimeout(fn, delay) schedules fn to run once, after at least delay milliseconds (never exactly that delay — only "no sooner than"). setInterval(fn, delay) repeats it every delay milliseconds until cleared.

const id = setInterval(() => console.log("tick"), 1000);
setTimeout(() => clearInterval(id), 5500); // stops it after roughly 5 ticks

A subtle setInterval gotcha: if fn itself takes longer to run than delay, intervals can queue up or overlap depending on the environment, rather than reliably firing at a fixed cadence — for anything where drift matters, a recursive setTimeout (scheduling the next call only after the current one finishes) is the more predictable pattern:

function poll() {
  doWork();
  setTimeout(poll, 1000); // schedules the NEXT call only after doWork() completes
}
setTimeout(poll, 1000);