Overview
Implement debounce(fn, delay) that returns a debounced function with .cancel() and .flush() methods.
.cancel()— cancels pending invocation.flush()— immediately invokes pending invocation
Examples
const d = debounce(fn, 100);
d('a'); d('b');
d.flush(); // immediately calls fn('b')Solution
Reveal solution
function debounce(fn, delay) {
let timer = null;
let lastArgs = null;
let lastThis = null;
function debounced(...args) {
lastArgs = args;
lastThis = this;
if (timer) clearTimeout(timer);
timer = setTimeout(() => { fn.apply(lastThis, lastArgs); timer = null; lastArgs = null; }, delay);
}
debounced.cancel = () => { if (timer) { clearTimeout(timer); timer = null; lastArgs = null; } };
debounced.flush = () => { if (timer) { clearTimeout(timer); timer = null; fn.apply(lastThis, lastArgs); lastArgs = null; } };
return debounced;
}debounce-enhanced.js
Debounce Enhanced
mediumcodingJavaScriptFunctions
Overview
Implement debounce(fn, delay) that returns a debounced function with .cancel() and .flush() methods.
.cancel()— cancels pending invocation.flush()— immediately invokes pending invocation
Examples
const d = debounce(fn, 100);
d('a'); d('b');
d.flush(); // immediately calls fn('b')Solution
Reveal solution
function debounce(fn, delay) {
let timer = null;
let lastArgs = null;
let lastThis = null;
function debounced(...args) {
lastArgs = args;
lastThis = this;
if (timer) clearTimeout(timer);
timer = setTimeout(() => { fn.apply(lastThis, lastArgs); timer = null; lastArgs = null; }, delay);
}
debounced.cancel = () => { if (timer) { clearTimeout(timer); timer = null; lastArgs = null; } };
debounced.flush = () => { if (timer) { clearTimeout(timer); timer = null; fn.apply(lastThis, lastArgs); lastArgs = null; } };
return debounced;
}NameTopicDifficulty
103 of 103 problems