Skip to content

CodeNot attempted

Debounce with cancel + flush

Difficulty: medium

Return a function that delays calling fn until wait ms have passed since the last call.

  • fn runs once, with the arguments and this of the last call
  • debounced.cancel() drops a pending call
  • debounced.flush() runs a pending call right now (and not again later); does nothing if nothing is pending
  • TypeScript: the debounced function must accept exactly fn's parameters. Write the return type yourself; the type tests check it.

Follow-up to be ready for: how would you add a leading option?

Show reference solution
export function debounce<T extends (...args: any[]) => void>(fn: T, wait: number) {
let timer: ReturnType<typeof setTimeout> | undefined;
let lastArgs: Parameters<T> | undefined;
let lastThis: unknown;
function debounced(this: unknown, ...args: Parameters<T>) {
lastArgs = args;
lastThis = this;
clearTimeout(timer);
timer = setTimeout(() => debounced.flush(), wait);
}
debounced.cancel = function () {
clearTimeout(timer);
lastArgs = undefined;
};
// Run the waiting call now, if there is one.
debounced.flush = function () {
clearTimeout(timer);
if (lastArgs) {
const args = lastArgs;
lastArgs = undefined;
fn.apply(lastThis, args);
}
};
return debounced;
}
Loading editor…