Glossary / setTimeout

setTimeout

setTimeout(callback, delay) schedules a one-shot callback to run no earlier than the requested delay, subject to host rules and event-loop availability. It returns immediately with a timer identifier; it does not block or pause the current function. The returned identifier can be passed to clearTimeout to cancel before the callback begins.

Scheduling, cancellation, and context

const id = setTimeout(() => console.log("later"), 250);
clearTimeout(id); // cancels if still pending

A delay of zero means “schedule for a later opportunity,” not “run now.” The current stack and microtasks complete first, and other work can delay the callback further. Browsers apply minimum delays to deeply nested timers and throttle background pages. Timer delays have finite host-specific ranges; do not encode long-term deadlines as one enormous timeout—persist a target time and reschedule safely.

Passing a method directly can lose its receiver because the host invokes the callback separately. Use an arrow closure or bind when needed. Avoid the string-code form; it evaluates code and interacts poorly with CSP/security. Use numeric delays, not strings that coerce. Timers are not accurate clocks; use performance.now() for elapsed durations and a wall-clock source for calendar time.

Cleanup

Store and clear timer IDs when the owning component/service stops. Repeatedly rescheduling without canceling can leave stale callbacks that update obsolete state. For async polling, schedule after work completes to avoid overlap and use AbortSignal or a disposed flag to stop lifecycle work.

Interview questions

  1. Does setTimeout(fn, 0) run before Promise callbacks? Usually no; Promise microtasks run before the timer task.
  2. Can clearTimeout stop an already-running callback? No; it only cancels a pending timer.
  3. Is timeout exact? No, delay is a lower bound and execution can be later.
  4. Why avoid passing a method directly? Its this receiver may be lost.

References