What is the difference between debouncing and throttling?
Quick Answer
Debounce — wait until events stop for X ms, then fire once (search-as-you-type: run the query only after the user pauses). Throttle — fire at most once per X ms while events keep coming (scroll/resize/mousemove handlers: update at a steady rate).
Both limit how often a handler runs during a flood of events, but the timing is different. Debouncing collapses a burst into one call that happens after things go quiet — perfect for a search box, where you only want to hit the API once the user stops typing for, say, 300ms. Throttling lets the handler run on a fixed cadence during the burst — once every 100ms no matter how many scroll events fire — which is what you want for updating a scroll position indicator. Implementation-wise debounce resets a timer on every event; throttle sets a cooldown and drops events until it expires.
- Debounce:
clearTimeoutthensetTimeouton every call; the callback runs only when the timer survives the interval. - Throttle: ignore calls until the cooldown elapses, then allow one and restart the cooldown.
- “Leading” vs “trailing” edge controls whether the first or last event in a burst is the one that fires.
- Use libraries (lodash) or small hand-rolled helpers; remember to cancel pending timers on component unmount.