JavaScript · The language round
What is the difference between debounce and throttle?
Short answer
Debounce waits until calls stop for a period before running once. Throttle runs at most once per period while calls keep coming. Debounce is for settling, throttle is for rate limiting.
Both reduce how often a function runs, but they answer different questions. Debounce asks whether the user has finished. Throttle asks how often the user is allowed to trigger work.
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);
}
};
}Which one to use
- Debounce: search suggestions, form validation, resize settling, autosave after typing stops
- Throttle: scroll handlers, drag events, analytics sampling, rate-limited UI updates
- Debounce can starve if the event never stops; throttle guarantees periodic execution
- Both should expose a
cancel()method when the component can unmount
Implementation details matter. A debounce can run on the leading edge, the trailing edge, or both. A throttle can allow the first call immediately and then space later calls. State the behaviour you need before choosing an implementation.
requestAnimationFrame is often a better throttle than a timer because it aligns work with the browser's paint cycle.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1When would you use debounce instead of throttle?
- 2How do you cancel a pending debounce?
- 3What is leading versus trailing debounce?
- 4Why is `requestAnimationFrame` useful for scroll updates?
Say it in the interview
Debounce waits until calls stop for a delay and then runs once, so it is good for search input or autosave. Throttle runs at most once per interval while calls continue, so it is good for scroll or drag handlers. Debounce can delay indefinitely if events never stop, while throttle guarantees periodic execution. I also make sure to cancel pending work when a component unmounts.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.