What is the difference between debounce and throttle?
Quick Answer
Debounce — wait until events stop for N ms, then fire once. Good for a search box: run the query after the user pauses typing. Throttle — fire at most once every N ms while events keep coming. Good for scroll/resize/mousemove handlers.
Debounce waits for a quiet period — you keep calling it, and it only actually runs once the calls stop for, say, 300ms. That's what you want for a search-as-you-type box: don't hit the API on every keystroke, wait until they pause. Throttle is a rate limit — it runs at most once every N milliseconds no matter how many times you call it — which is right for a scroll or resize handler where you want regular updates but not one per pixel.
- Debounce resets its timer on every call; throttle ignores calls until the cooldown passes.
- Both can fire on the leading edge (immediately) and/or trailing edge (after the wait) — configurable.
- Lodash has both; a hand-rolled debounce is ~5 lines with
setTimeout/clearTimeout. - In React, debounce a callback with
useMemo/useRefso it isn't recreated each render.
function debounce(fn, wait) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), wait);
};
}
searchInput.addEventListener('input', debounce(runSearch, 300));