Question presented to candidate: "Take a standard debounce implementation and extend it so callers can cancel a pending call before it fires. Prove that cancelling actually prevents execution."
What a strong answer should cover:
- The base debounce mechanism is unchanged — a closure clearing and restarting a single timer id per call.
.cancel()is attached as a property on the RETURNED debounced function, and it simply callsclearTimeouton the same timer id the debounce logic already closes over, then resets it.- Because it is the exact same closure variable, no separate tracking is needed — cancel is a thin, three-line addition on top of the existing mechanism, not a redesign.
- Calling cancel after the delay has already elapsed (nothing pending) should be a safe no-op, not an error.
- Real verification: proving with a real timer that cancelling before the delay elapses genuinely prevents the wrapped function from ever running, not just assuming clearTimeout works from documentation.
Clarifying questions expected:
- "Should calling cancel() when nothing is pending throw, or silently do nothing?" (a strong candidate flags this edge case and defaults to a safe no-op)
- "Do you also need a .flush() method to run the pending call immediately, or is cancel enough for this question?" (shows awareness of the related, but distinct, lodash-style API surface)
Code / implementation expected: Yes — a full working debounce-with-cancel implementation, executed with real timing proving cancel-before-firing genuinely prevents the call.