Skip to solution
mediumFrontend

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

397 views
01

Understand 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.

utilitytrickyreal-world
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Target Audience: Engineers preparing for JavaScript / frontend-implementation interview questions. Difficulty: Medium

How to read this doc: Concepts are explained in plain language first, then tagged with 📌 Interview term:. Every result below was actually run on Node.js v24.19.0 — the print

Solution ready — 2 min read

Classified // press E to declassify

04

Run the code

JSDebounce with a working .cancel() method (run directly)
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 96 of 165 decoded in the JavaScript track. One more won't hurt.

Back to track