Implement Debounce

MediumUtility Functions15 min5 tests

Implement a debounce function that delays invoking the provided function until after wait milliseconds have elapsed since the last time it was invoked.

Requirements

  • The debounced function should delay execution
  • If called again before the delay expires, restart the timer
  • The function should be invoked with the correct this context and arguments

Example

const debouncedFn = debounce(() => console.log('Called!'), 300);
debouncedFn(); // Nothing happens immediately
// After 300ms of no calls: "Called!"
Hints (5)
  1. You need to return a new function that wraps the original function.
  2. Use setTimeout to delay the execution and store its ID in a variable.
  3. Use clearTimeout to cancel any pending execution when called again.
  4. Remember to preserve the this context using apply or call.
  5. Store the timeout ID in a closure variable that persists between calls.

Topics

  • Utility Functions

Asked at

Google · Meta · Amazon · Uber

Loading the sandbox…

Join Us
blur