Debounce vs throttle
EasyJavaScriptPerformanceEvents
What's the difference between debounce and throttle, and when do you use each?
TL;DR
Both limit how often a function runs in response to rapid events. Debounce waits until the events stop for a given delay, then runs once. Throttle runs at most once per interval while events keep coming. Debounce when you only care about the final value (search input). Throttle when you need steady updates during the activity (scroll or resize handlers).
Key points
- Debounce: each new event resets the timer. Typing "react" with a 300 ms debounce sends one request, after the user pauses.
- Throttle: the first call runs, then further calls are ignored (or the last one is queued) until the interval passes.
- Leading vs trailing: whether the call fires at the start of the burst, the end, or both. Lodash exposes both options.
- For scroll-linked visuals,
requestAnimationFrameis often better than a time-based throttle, andIntersectionObserverreplaces many scroll listeners entirely. - In React, keep the debounced function stable (
useMemooruseRef) and cancel it on unmount.
Example
js
function debounce(fn, delay) {
let timer
return (...args) => {
clearTimeout(timer)
timer = setTimeout(() => fn(...args), delay)
}
}
function throttle(fn, interval) {
let last = 0
return (...args) => {
const now = Date.now()
if (now - last >= interval) {
last = now
fn(...args)
}
}
}
input.addEventListener(
'input',
debounce((e) => search(e.target.value), 300),
)
window.addEventListener('scroll', throttle(updateProgressBar, 100))Common follow-ups
- Does debouncing a search fix race conditions? No. Slow old responses can still arrive after new ones; cancel them with
AbortControlleror ignore stale results. - Why does a debounce inside a React component not work? A new debounced function is created on every render, so each keystroke has its own timer.
What interviewers look for
Tip
One crisp distinction ("after it stops" vs "at most every N ms"), a matching use case for each, and a working implementation using a closure.
- Red flag: mixing the two up, or creating a fresh debounced function on every render.