What is the difference between debounce and throttle? When do you use each?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Debounce delays execution until events stop firing for a wait period — only the last call runs. Throttle guarantees execution at most once per interval. Debounce for search inputs; throttle for scroll/resize handlers.
Detailed explanation
Both limit how often a function executes under rapid event bursts, but they answer different questions. Debounce asks 'has the user stopped?' — every new event resets a timer, so the function fires once, after quiet. Ideal when only the final state matters: autosaving after typing pauses, validating a form field, resizing calculations. Throttle asks 'is it time again?' — the function runs at a fixed maximum rate regardless of burst size, ensuring regular feedback during continuous activity: scroll position indicators, drag movements, analytics sampling, game loops. Implementation-wise, debounce stores one timeout handle that gets cleared on each call; throttle stores a last-run timestamp (often plus a pending flag for the trailing call). Interviewers love asking you to implement either from scratch on a whiteboard.
Example
function debounce(fn, wait = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
function throttle(fn, interval = 300) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn(...args);
}
};
}
searchInput.addEventListener('input', debounce(e => search(e.target.value)));
window.addEventListener('scroll', throttle(updateProgressBar, 100));Interview tip
Lead with the mnemonic — debounce = 'wait for silence', throttle = 'steady drip' — then implement debounce live if asked; it's ~6 lines and interviewers frequently request it.
Common mistakes
- Swapping the two use cases in examples.
- Forgetting to pass through arguments (...args) in the returned wrapper.