Sequence NODE_156
MediumImplement a Debounce Function
JavaScript
Technical Specification
Implement a debounce function that delays invoking a callback until after a certain wait time has elapsed since the last call.
Input/Output Samples
Input:debounce(fn, 300)
Output:fn runs only once after user stops triggering for 300ms
Optimal Logic Path
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}Architectural Deep-Dive
debounce returns a wrapper that resets the timer on every call. The original function only runs when no new calls arrive within the delay.