Implement debounce
Write debounce(fn, wait) that returns a debounced version of fn: it waits until wait ms have passed since the last call, then calls fn once with the latest arguments and the latest this. Nothing runs right away (there is no leading call).
d(1); d(2); d(3)in quick succession →fn(3)runs once,waitms after the last call- with
wait = 60:d('a'), thend('b')30ms later → onlyfn('b')runs, at about 90ms obj.save = debounce(fn, 100); obj.save(1)→fnis called withthis === objd(); d.cancel()→fnnever runs
The returned function must also have a cancel() method that drops any pending call. After a cancel, or after a call has fired, the debounced function keeps working as normal.
Define debounce in the editor. 6 tests will call it.
Hint 1Keep the timer id in a variable inside debounce. Every call clears the previous timer and starts a new one.
Hint 2Return a regular function so you can capture this and ...args, then call fn.apply(this, args) from an arrow function inside setTimeout (the arrow keeps the outer this).
Hint 3cancel only needs to clearTimeout the pending timer. Functions are objects, so attach it as a property: debounced.cancel = () => { ... }.
one clean solution
function debounce(fn, wait) {
let timer = null;
function debounced(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, wait);
}
debounced.cancel = () => {
clearTimeout(timer);
timer = null;
};
return debounced;
}