Debounce

UtilitiesLogic

Implement a debounce function that delays the execution of a function until after a specified amount of time has passed since it was last invoked.

Function Signature:

function debounce(func, wait)

Requirements:

  • The function should delay execution until wait milliseconds have passed since the last call
  • Each new call should reset the timer
  • Only the last call should execute after the delay period
  • Arguments passed to the debounced function should be preserved

Examples

Example 1
Input
const log = () => console.log('Fired!');
const debouncedLog = debounce(log, 1000);

debouncedLog();
debouncedLog();
debouncedLog();
// Wait 1 second...
Output
Fired!
Explanation
Even though `debouncedLog` is called three times, it only executes once after 1 second because each call resets the timer. Only the final call executes.
Example 2
Input
const greet = (name, greeting) => {
  console.log(`${greeting}, ${name}!`);
};
const debouncedGreet = debounce(greet, 500);

debouncedGreet('Alice', 'Hello');
debouncedGreet('Bob', 'Hi');
setTimeout(() => debouncedGreet('Charlie', 'Hey'), 100);
// Wait 500ms after the last call...
Output
Hey, Charlie!
Explanation
The first two calls are cancelled. The third call (after 100ms) resets the timer, and after 500ms from that call, it executes with the arguments 'Charlie' and 'Hey'.

Constraints

  • The function should handle any number of arguments
  • The timer should reset on every call
  • If called multiple times rapidly, only the last call should execute

Notes

  • Use closures to maintain the timer state
  • Consider edge cases like `wait` being 0 or negative
  • Make sure to clear the previous timer before setting a new one

Hints

Read the full write-up for Debounce
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it