DebounceLoading saved progress…

Debounce

You've used a search box that fires a request on every keystroke and floods the network, or a window-resize handler that runs hundreds of times during a single drag. Debouncing is the standard fix: wait until the user pauses, then act once on the final state.

Implement a debounce function that, given a callback fn and a delay wait (ms), returns a new function. The returned function delays invoking fn until wait milliseconds have elapsed since the last time it was called. If it's called again within wait, the previous timer is cleared.

Signature

function debounce(fn, wait) {
  // returns a new function that, when called repeatedly,
  // only invokes `fn` once after `wait` ms of inactivity
}

Examples

const log = debounce((msg) => console.log(msg), 100);
log('a');
log('b');
log('c');
// After 100ms of silence: logs 'c' only

Notes

  • Use setTimeout and clearTimeout — no external libraries.
  • Each call must reset the timer.
  • When the debounced function is called as a method on an object (e.g. obj.onInput()), this inside fn must still refer to that object — not to undefined or the global object.
  • Don't worry about cancel / flush methods for v1.
Loading editor…