Performance and DevTools
Debounce and throttle repeated input
Choose between waiting for a burst to finish and limiting work to a steady maximum rate.
8 minute lesson
Repeated events can arrive faster than the associated work should run. Debouncing and throttling express two different product decisions.
A debounce waits until events have stopped for a chosen delay:
let timer
search.addEventListener('input', () => {
clearTimeout(timer)
timer = setTimeout(() => runSearch(search.value), 250)
})
This suits an autocomplete request when intermediate values are not useful. Its tradeoff is deliberate latency: the result cannot start until the pause has elapsed.
A throttle allows work at a limited rate while events continue. It suits progress indicators or analytics that must update during activity without processing every event.
For visual scroll and pointer work, a useful variation is to save the latest state and apply it once in requestAnimationFrame(). This aligns updates with rendering and avoids building a backlog of obsolete positions.
Choose from the desired behavior:
- Need only the final value after a burst? Debounce.
- Need periodic updates during the burst? Throttle.
- Need the latest visual state for each frame? Schedule one frame callback.
Cancellation and cleanup are part of the design. Clear pending timers or frame callbacks when their component is destroyed, and decide whether the first or final event must always run.
Record a fast typing or scroll interaction before and after applying the chosen strategy. Confirm that handler work decreases without making the interface feel disconnected.
Lesson completed