JavaScript Interview Question #120
What is debouncing?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
Debouncing delays a function until a specified quiet period has passed since the most recent call. Repeated calls reset the timer, so only the final call after activity stops is normally executed.
Detailed Explanation
Debouncing delays a function until a specified quiet period has passed since the most recent call. Repeated calls reset the timer, so only the final call after activity stops is normally executed.
It is useful for search boxes, resize handling, validation, and other high-frequency events where running expensive work for every event would be wasteful.
Code Example
function debounce(fn, delay) {
let timerId;
return (...args) => {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn(...args);
}, delay);
};
}
const search = debounce(
value => console.log("Search:", value),
300
);