All topics
Asyncbeginner

setTimeout, setInterval, and Timer Precision

Scheduling delayed or repeating code execution, and why the delay argument is a minimum, not a guarantee.

setTimeout and setInterval are the APIs for scheduling code after a delay or repeatedly, often the first async API developers encounter. The delay is a minimum wait time, not a precise guarantee, since JS's single-threaded model can always delay a callback further.

setTimeout is like setting a kitchen timer and doing other chores — the buzzer doesn't yank you away immediately, you finish what you're doing first.

Key Concepts

1
setTimeout(callback, delay) runs callback once after at least delay ms, returning an ID for clearTimeout. setInterval keeps firing every delay ms until cleared with clearInterval — forgetting to clear one is a classic memory leak.
2
The 'minimum, not guarantee' behavior comes from the event loop: a timer callback waits behind the current call stack and the entire microtask queue. A busy main thread can push actual execution far later than the specified delay.
3
Browsers clamp minimum delays and setInterval can drift over iterations since delay is measured from scheduling, not a fixed origin; a recursive setTimeout is often preferred for drift-free timing.