Learn JavaScript
❯ async.timers

Timers: setTimeout, setInterval & debounce in JavaScript

$concept

Timers schedule macrotasks: setTimeout runs once after a minimum delay (clamped, throttled in background tabs), setInterval repeats (drifting under long tasks — recursive setTimeout self-corrects), both return clearable handles. They guarantee earliest-run, never exact timing.

Two patterns dominate: debounce (restart the timer per event — search-as-you-type) and throttle (at most once per window — scroll/resize handlers). Always clear timers on teardown (components, tests) — stray intervals are a premier leak and flake source.

$how it works
1

Timeout runs once

setTimeout(fn, ms) queues one execution no sooner than ms — minimum, never exact.

2

Interval repeats (with drift)

setInterval schedules blindly — long tasks delay ticks; recursive setTimeout spaces executions evenly instead.

3

Debounce waits for quiet

Reset the timer on each event; fire only after silence — search inputs, autosave, resize-end.

4

Clear on teardown

clearTimeout/clearInterval with stored handles — unmounted components must not fire timers.

$example
function debounce(fn, ms) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), ms);
};
}
let log = debounce((x) => console.log("got", x), 50);
log(1);
log(2);
Output
(after 50ms quiet: got 2)
1debounce returns a wrapper holding timer handle t in closure.
2log(1) arms the timer; log(2) clears it and rearms — only the latest survives.
3After 50ms without calls, got 2 fires once — intermediate values never emitted.
$use cases
Search-as-you-type with debounced fetching
Scroll/resize handlers throttled to animation frames
Recursive setTimeout for drift-free polling
Clearing every timer on component unmount and test teardown

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.