Q26: Implement a debounce function from scratch.
Answer
Debouncing delays function execution until a specified period has elapsed since the last call. It is useful for search inputs, resize handlers, and other frequently triggered events.
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
const search = debounce(query => {
console.log("Searching for:", query);
}, 300);
search("j");
search("ja");
search("javascript");
// After approximately 300 ms without another call:
// Searching for: javascript
Explanation
Each invocation clears the previous timer and creates a new timer. Only the last scheduled invocation executes if no additional call occurs before the delay expires.
Common interview follow-up
How would you add an immediate execution option? A leading-edge debounce executes on the first call in a burst and suppresses subsequent calls until the waiting period ends. A production-ready debounce utility may also support trailing execution, cancellation, flushing, and return-value handling.
Key Takeaways
- Debounce postpones execution until calls stop for a specified interval.
- It is useful when only the latest input matters.