Debounce vs Throttle
Implement debounce and explain when you'd throttle instead (e.g., scroll handlers).
Answers use simple, clear English.
Quick interview answer
Debounce waits until calls pause for N ms — good for search-as-you-type. Throttle ensures at most one call per interval — good for scroll/resize where you want periodic updates. Both reduce work; pick based on whether you need the trailing quiet value or steady sampling.
Detailed answer
Debounce waits until calls pause for N ms — good for search-as-you-type. Throttle ensures at most one call per interval — good for scroll/resize where you want periodic updates. Both reduce work; pick based on whether you need the trailing quiet value or steady sampling.
Real example & use case
Search box debounced 300ms; infinite-scroll loader throttled to 200ms.
Pros & cons
Pros: less server/UI load. Cons: over-debounce feels laggy; wrong choice hurts UX.
Code example
function debounce(fn, wait) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), wait);
};
}Practice code · javascript (view only · no execution)
function debounce(fn, wait) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), wait);
};
}