QuestionsWeb Performance

Debounce vs. throttle

Event HandlingEasyWeb Performance

A scroll/resize/input handler is firing far too often and janking the page. When do you debounce and when do you throttle? Implement both.

What it tests

Choosing the right rate-limiting strategy and being able to write each from scratch.

Approach & answer

Both limit how often an expensive handler runs, but with opposite timing semantics. DEBOUNCE waits for a pause: it fires only after events STOP for N ms, collapsing a burst into one call at the end. Use it when you only care about the final state — a search-as-you-type input (query the API once the user stops typing), resize (relayout once they finish dragging), validating a field after typing ends. THROTTLE guarantees a steady cadence: it fires at most once every N ms DURING a continuous stream, giving you regular updates while the burst is ongoing. Use it when you need periodic feedback mid-stream — scroll position (update a progress bar/parallax as they scroll), mousemove drawing, firing analytics at a bounded rate. Mnemonic: debounce = 'wait until they're done', throttle = 'at most once per interval'. Both slash the number of times your costly work (layout reads, network calls, React state updates) runs, which is often the difference between a smooth 60fps and a janky handler. For scroll specifically, IntersectionObserver or a passive listener + rAF is often better than throttle; but for input, debounce remains the go-to. Watch the leading/trailing edge option — a leading-edge debounce fires immediately then suppresses, which feels more responsive for some UIs.

Use this technique when

Rate-limiting input, scroll, resize, or mousemove handlers to stop excessive work.

Complexity

O(1) per event; work runs at most once per pause (debounce) or per window (throttle)

References

js