Skip to the solution
MediumFrontend6 min read

How would you implement a debounce utility that also exposes a .cancel() method to cancel a pending call?

397 views

The problem

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 calls clearTimeout on 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.

  • utility
  • tricky
  • real-world

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read Β· 7 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptDebounce with a working .cancel() method (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 96 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How do you make an AJAX request?

Continue