What is the difference between debounce and throttle in JavaScript?
- Technology:
- JavaScript
Quick answer
Debounce waits until the user stops triggering an event for a set time before running the function; throttle runs the function at most once per time interval no matter how often the event fires.
Detailed explanation
Use debounce when only the final value matters, such as a search box that should call the API after the user pauses typing. Use throttle when you want regular updates during continuous activity, such as scroll position tracking or window resize handling.
Both are built with closures and timers. In React, make sure the debounced function is created once (for example with useMemo or useRef), otherwise every render creates a new timer and the debounce does nothing.
Example
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
function throttle(fn, limit) {
let waiting = false;
return (...args) => {
if (waiting) return;
fn(...args);
waiting = true;
setTimeout(() => { waiting = false; }, limit);
};
}Key points
- Debounce: run after the burst ends
- Throttle: run at a steady maximum rate
- Both rely on closures to keep the timer between calls