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
thiscontext and arguments
Example
const debouncedFn = debounce(() => console.log('Called!'), 300);
debouncedFn(); // Nothing happens immediately
// After 300ms of no calls: "Called!"Hints (5)
- You need to return a new function that wraps the original function.
- Use
setTimeoutto delay the execution and store its ID in a variable. - Use
clearTimeoutto cancel any pending execution when called again. - Remember to preserve the
thiscontext usingapplyorcall. - Store the timeout ID in a closure variable that persists between calls.
Topics
- Utility Functions
Asked at
Google · Meta · Amazon · Uber
