Problem Statement
Explain debounce and throttle. When would you use each?
Explanation
Debounce delays execution until a burst of events stops. Use it for search input or resize handlers so a function runs only after the user stops typing/resizing.
Throttle guarantees execution at most once per interval during a continuous event stream. Use it for scroll or mousemove to run a handler at a controlled rate.
Both techniques improve performance and user experience.
Code Solution
SolutionRead Only
// Debounce
function debounce(fn, delay){
let t; return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), delay); };
}
// Throttle
function throttle(fn, interval){
let last = 0; return (...args) => {
const now = Date.now();
if (now - last >= interval){ last = now; fn(...args); }
};
}Practice Sets
This question appears in the following practice sets:
