Timers: setTimeout, setInterval & debounce in JavaScript
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.
Timeout runs once
setTimeout(fn, ms) queues one execution no sooner than ms — minimum, never exact.
Interval repeats (with drift)
setInterval schedules blindly — long tasks delay ticks; recursive setTimeout spaces executions evenly instead.
Debounce waits for quiet
Reset the timer on each event; fire only after silence — search inputs, autosave, resize-end.
Clear on teardown
clearTimeout/clearInterval with stored handles — unmounted components must not fire timers.
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);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.