Loading...
Loading...
0 <= delay <= 10000 (milliseconds) fn is a valid JavaScript function The debounced function may be called 0 or more times Arguments passed to the debounced function can be of any type
In frontend development, debouncing is a critical performance optimization technique. When users perform rapid actions (typing in a search box, resizing a window, clicking a button repeatedly), you often want to delay execution of a handler until the user has stopped performing the action for a given period.
Your task is to implement a debounce function from scratch in JavaScript.
Implement a debounce(fn, delay) function that returns a debounced version of the provided function fn. The debounced function, when called repeatedly, will only execute fn once after the user has stopped calling it for delay milliseconds.
Key behaviors:
fn is only called after the debounced function has not been called for delay milliseconds.this context and forward all arguments to fn.cancel method that, when called, cancels any pending execution.Input:
fn — A function to be debounced.delay — A non-negative integer representing the delay in milliseconds.Output:
fn, plus an additional .cancel() method.const log = debounce((msg) => console.log(msg), 300);
log('hello'); // timer starts
log('world'); // timer resets
// After 300ms of inactivity → logs: 'world'
Explanation: Only the last call's argument is used, and fn fires once after the delay.
const log = debounce((msg) => console.log(msg), 500);
log('fire'); // timer starts
log.cancel(); // timer cancelled
// Nothing is logged
Explanation: Calling .cancel() clears the pending timer so fn never executes.
const add = debounce((a, b) => a + b, 0);
add(2, 3);
// After 0ms → executes with (2, 3), result: 5
Explanation: Even with delay = 0, execution is deferred to the next event loop tick.
setTimeout and clearTimeout to manage the delay timer....args) to capture all arguments and forward them to fn..cancel as a property on the returned wrapper function.this binding — use an arrow function or .apply() to preserve context.