Debounce II
Problem statement
Implement an advanced debounce function. Debouncing controls how many times a function is allowed to execute over time.
When a function is debounced with a wait time of X milliseconds, the callback should run only after X milliseconds have elapsed since the last call to the debounced function.
Extra Methods
cancel(): cancel any pending invocation.flush(): immediately invoke any pending delayed invocation.
Requirements
- Preserve the latest arguments and
thisbinding. - Reset the timer on every call.
cancel()should clear the timer and forget pending arguments.flush()should execute immediately only when there is a pending invocation.
Requirements & constraints
- Do not use external libraries.
- Preserve `this` and arguments.
- Expose `cancel` and `flush` methods on the returned function.
How to approach Debounce II
The strategy an interviewer expects you to reach for.
Debounce II is the “search box” helper with cancel/flush control — wait until typing pauses, optionally force-run or abort. Naive move Basic debounce without remembering this/args, or without cancel when the component unmounts. Where it breaks Trailing call must use the latest arguments. cancel should clear the timer without invoking. flush should invoke immediately if pending. The fix Closure over timerId, lastArgs, lastThis. Each call resets the timer. On fire, invoke with stored args/this. Expose cancel/flush on the wrapper if the prompt requires them. Remember: Reset the timer every call; keep latest args/this for the trailing invoke. Say this in the interview: I'd debounce by clearing and resetting a timer on every call, invoke with the latest args and this, and provide cancel/flush for lifecycle control.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.