Async JavaScript
Timers, Scheduling & Debouncing
Timers schedule future tasks, but they are not precise clocks. Debouncing and throttling shape frequent events so expensive work runs at a controlled rate.
- Timer delay is a minimum, not a guarantee
- Debounce waits for quiet
- Throttle enforces a maximum rate
- Intervals can overlap conceptually
- Fake timers make time testable
| Pattern | Behavior | Best for |
|---|---|---|
| setTimeout | Run once after delay | Timeouts, delayed work |
| setInterval | Run repeatedly | Simple polling |
| Debounce | Run after quiet period | Search input |
| Throttle | Run at most every N ms | Scroll/drag events |
| requestAnimationFrame | Before browser paint | Visual updates |
function debounce(fn, delay) {
let id
return (...args) => {
clearTimeout(id)
id = setTimeout(() => fn(...args), delay)
}
}
const search = debounce((query) => fetchResults(query), 300)