Debounce vs throttle
Imagine a user typing seven characters into a search field. The input event can fire seven times, but you may not want seven search requests. Debounce and throttle are two ways to control how often the handler runs.
The distinction
Section titled “The distinction”| Pattern | Rule | Typical use |
|---|---|---|
| Debounce | Wait for a quiet period, then run once. | Search input, autocomplete, validation |
| Throttle | Run at most once per time interval while events continue. | Scroll, resize, pointer movement |
If events arrive every 100 ms and the delay is 500 ms:
Events: ● ● ● ● ● ● ● stopDebounce: ●Throttle: ● ● ●The exact throttle calls depend on whether it runs at the start or end of an interval. The useful distinction is that debounce waits for a pause, while throttle can keep working during activity.
Search input: choose debounce
Section titled “Search input: choose debounce”As the user types J → Je → Jee → Jeewan, a debounced search waits until typing pauses. Then it sends the latest value.
const search = debounce((query) => fetchResults(query), 500);search('J');search('Je');search('Jee');search('Jeewan');// One call with "Jeewan" after 500 ms without another call.See the debounce implementation for a complete function.
Scroll tracking: choose throttle
Section titled “Scroll tracking: choose throttle”Scroll events may fire many times each second. A throttled handler updates at a controlled rate while scrolling continues.
const updatePosition = throttle(() => { console.log(window.scrollY);}, 200);
window.addEventListener('scroll', updatePosition);See the throttle implementation for a complete function.
Interview answer
Section titled “Interview answer”Debounce waits for a pause in activity before running. Throttle limits execution to a fixed rate during continuing activity. I would usually debounce search input and throttle scroll or resize work.
Check your understanding
Section titled “Check your understanding”A user drags a slider, and the screen should update regularly during the drag. Throttle is the better starting point. If the update should happen only after the user releases the slider, start with debounce.