Debounce Wrapper with Leading-Edge Mode
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a higher-order debounce utility driven by the FakeTimers virtual millisecond scheduler provided in starter.py:
def debounce(
func: Callable[..., Any],
wait: int,
timers: FakeTimers,
leading: bool = False,
) -> Callable[..., None]: ...
When callers invoke the returned wrapper repeatedly in quick succession, consecutive calls separated by strictly fewer than wait milliseconds belong to the same burst, and every call resets the wait-millisecond timer:
- Trailing mode (
leading=False, default):funcexecutes once per burst, exactlywaitmilliseconds after the final call in that burst, receiving that final call's positional and keyword arguments (*args, **kwargs). Earlier calls in the burst are superseded. - Leading mode (
leading=True):funcexecutes immediately on the first call of a burst with that call's*argsand**kwargs. Every subsequent call arriving beforewaitquiet milliseconds have elapsed resets thewait-millisecond cooldown and is otherwise ignored (no trailing execution occurs when the cooldown ends). - Bound methods passed as
funcmust retain their bound object instance, the wrapper always returnsNone, and independent calls todebouncemust not share state. - Raise
ValueErrorifwait < 0.
Examples
Example 1
Input:
timers = FakeTimers()
log = []
debounced = debounce(lambda q: log.append((timers.now, q)), 250, timers)
debounced("py") # t = 0 ms
timers.advance(100)
debounced("pyt") # t = 100 ms
timers.advance(120)
debounced("python") # t = 220 ms
timers.advance(249) # t = 469 ms (log checked here, then +1 ms)
timers.advance(1) # t = 470 ms
Output:
At t = 469 ms: log == []
At t = 470 ms: log == [(470, "python")]
Explanation: "py" at 0 ms schedules a run for 250 ms, "pyt" at 100 ms cancels it and reschedules for 350 ms, and "python" at 220 ms cancels again and reschedules for 470 ms. Nothing fires through 469 ms; at 470 ms, 250 ms of silence have elapsed, so func("python") runs once with the latest arguments.
Example 2
Input:
timers = FakeTimers()
log = []
debounced = debounce(lambda r: log.append((timers.now, r)), 300, timers, leading=True)
debounced("req-1") # t = 0 ms
timers.advance(180)
debounced("req-2") # t = 180 ms
timers.advance(220)
debounced("req-3") # t = 400 ms
timers.advance(350) # t = 750 ms
debounced("req-4") # t = 750 ms
Output:
log == [(0, "req-1"), (750, "req-4")]
Explanation: "req-1" opens a burst at 0 ms and executes right away. "req-2" (180 ms after "req-1") and "req-3" (220 ms after "req-2") both arrive within the 300 ms window, so both are suppressed while pushing the cooldown deadline out to 700 ms (400 + 300). By 750 ms the cooldown has expired without a trailing call, so "req-4" begins a fresh burst and runs immediately.
Constraints
waitis an integer (wait >= 0is valid, includingwait == 0;wait < 0raisesValueError).- Each call to the debounced wrapper must execute in
O(1)time and maintainO(1)pending timers per wrapper, even under rapid bursts of thousands of calls. - Re-entrant calls made inside
funcmust work cleanly: calling the wrapper during a trailing run begins a new burst, whereas calling it synchronously during a leading run stays suppressed inside the current cooldown.
Step-by-step walkthrough
Restate the problem and timer contract
debounce(func, wait, timers, leading=False)is a higher-order function (a function that takes a function as input and returns a new wrapper function). When callers invoke the wrapper repeatedly in a fast burst—such as keystrokes in a search bar or rapid window-resize events—the wrapper collapses the entire burst into one call tofunc.In
starter.py, timer scheduling is modeled deterministically withFakeTimers(standing in for JavaScript'ssetTimeout/clearTimeoutor an event-loop scheduler):timers.set_timeout(callback, delay)andtimers.clear_timeout(timer_id)schedule and cancel callbacks on a virtual millisecond clock (timers.now), advancing viatimers.advance(ms)without sleeping in real wall-clock time.*args, **kwargsand bound methods: in Python, passing a bound method likeaccount.savealready carries its receiver instance inside the callable object, and*args, **kwargsforwards all positional and keyword arguments intact.- Validation:
leadingdefaults toFalse, andwait < 0raisesValueError.
Trace both modes on a concrete millisecond timeline
Define a burst as a sequence of calls where every consecutive pair is separated by strictly less than
waitmilliseconds. Crucially, every call resets thewait-millisecond countdown, so a burst ends only afterwaitfull milliseconds of silence.Suppose
wait = 250ms and a user calls the wrapper att = 0,100, and220ms:Time (ms): 0 100 220 470 Incoming calls: call("py") call("pyt") call("python") (250 ms of silence) Active timer: [0 -> 250) X cancelled at 100 [100 -> 350) X cancelled at 220 [220 ----------------> 470] fires! leading=False: (wait) (wait) (wait) func("python") runs! leading=True: func("py") ignored ignored cooldown ends (no call)Notice two important behavioral rules:
- Leading mode does not also fire at the trailing edge: when
leading=True, later calls inside the burst are suppressed rather than saved for a trailing execution (whereas libraries like Lodash expose a separatetrailingflag that defaults totrue; worth noting aloud in an interview). - Leading mode still extends the quiet window on every call: if calls arrive at
0,180, and400ms withwait = 300,"req-2"and"req-3"keep pushing the cooldown out to700ms. Only after300ms of complete silence does the next call start a new burst (unlike throttling, which fires on a fixed periodic schedule during non-stop input).
- Leading mode does not also fire at the trailing edge: when
Key idea: track burst state with two closure variables
Each call to
debounce(...)creates its own closure (an inner scope that remembers local variables from the outerdebouncecall even afterdebouncereturns), so two debounced wrappers never interfere with each other.We do not even need to store timestamps! Whether a timer is currently scheduled already tells us whether a burst is active:
timer_id: the integer ID of the currently pending timer, orNonewhen no burst is in progress.pending_call: a(args, kwargs)tuple holding the latest call's arguments whenleading=False, orNonewhen nothing is waiting to run.
Idle state (between bursts): timer_id = None, pending_call = None Active trailing burst: timer_id = 3, pending_call = (("python",), {}) Active leading cooldown: timer_id = 3, pending_call = NoneCode the timeout callback and protect re-entrant calls
When
waitms of silence finally pass,on_timeout()runs. Its job is to mark the burst finished (timer_id = None) and, in trailing mode, runfuncwith the saved latest arguments.Pay close attention to the order of lines inside
on_timeout(): we resettimer_id = Noneandpending_call = Nonebefore callingfunc(*saved_args, **saved_kwargs). Why? Supposefuncitself calls the debounced wrapper again (for example, saving a draft triggers a follow-up state update). If we clearedtimer_idandpending_callafterfuncreturned, we would accidentally wipe out the brand-new timer and arguments thatfuncjust scheduled!if wait < 0: raise ValueError("wait must be non-negative") # timer_id: active timer ID ending the current burst, or None when idle timer_id: Optional[int] = None # pending_call: (args, kwargs) of the latest call waiting for trailing execution pending_call: Optional[Tuple[Tuple[Any, ...], Dict[str, Any]]] = None def on_timeout() -> None: nonlocal timer_id, pending_call # Reset burst state BEFORE invoking func so a re-entrant call inside func # starts a clean new burst instead of having its state overwritten. timer_id = None if pending_call is None: # In leading mode, pending_call stays None: timeout simply ends cooldown return saved_args, saved_kwargs = pending_call pending_call = None func(*saved_args, **saved_kwargs)Code the wrapper for both trailing and leading edges
Inside
debounced(*args, **kwargs), four small steps run in a deliberate order:- Check leading eligibility first:
should_run_now = leading and (timer_id is None). We must compute this before scheduling the new timer, because afterwardtimer_idis neverNone. - Cancel the previous timer: if
timer_id is not None, calltimers.clear_timeout(timer_id)so earlier calls in the burst never fire early. - Save arguments and schedule the fresh timer: in trailing mode, overwrite
pending_call = (args, kwargs)so the latest arguments win; in both modes, scheduletimer_id = timers.set_timeout(on_timeout, wait). - Run
funclast ifshould_run_now: scheduling the timer before callingfuncguarantees that iffuncsynchronously callsdebounced(...)again (or raises an exception),timer_idis already non-None, preventing a double immediate execution or an uncancelled timer leak.
def debounced(*args: Any, **kwargs: Any) -> None: nonlocal timer_id, pending_call # Phase 1: check leading-edge eligibility BEFORE updating timer_id should_run_now = leading and (timer_id is None) # Phase 2: cancel any in-flight timer so every call restarts the wait window if timer_id is not None: timers.clear_timeout(timer_id) # Phase 3: store latest arguments for trailing mode, and schedule new timer # BEFORE calling func so a synchronous nested call sees timer_id != None if not leading: pending_call = (args, kwargs) timer_id = timers.set_timeout(on_timeout, wait) # Phase 4: fire immediately on the first call of a burst when leading=True if should_run_now: func(*args, **kwargs) return debounced- Check leading eligibility first:
Walk through Examples 1 and 2 step by step
Trace both examples from
statement.md:Example 1: leading=False, wait=250 ms Time Event timer_id pending_call Output ---- -------------------------- -------- ---------------- -------- 0 debounced("py") 1 (@250) (("py",), {}) - 100 debounced("pyt") (cancels 1) 2 (@350) (("pyt",), {}) - 220 debounced("python") (canc 2) 3 (@470) (("python",), {}) - 470 timer 3 fires None None "python" Example 2: leading=True, wait=300 ms Time Event timer_id pending_call Output ---- -------------------------- -------- ---------------- -------- 0 debounced("req-1") 1 (@300) None "req-1" (runs now) 180 debounced("req-2") (canc 1) 2 (@480) None - (ignored) 400 debounced("req-3") (canc 2) 3 (@700) None - (ignored) 700 timer 3 fires None None - (cooldown over) 750 debounced("req-4") 4 (@1050) None "req-4" (runs now)JavaScript equivalent with this-binding
In JavaScript, the exact same 4-phase structure works with one language-specific rule: return a standard
function debounced(...args)(not an arrow function(...args) =>) so JavaScript binds dynamicthisfrom the call site (obj.method()setsthis === obj), and invokefunc.apply(context, args):function debounce(func, wait, options = { leading: false }) { if (wait < 0) { throw new RangeError("wait must be non-negative"); } const leading = Boolean(options && options.leading); let timerId = null; let pendingCall = null; // { context, args } of the latest call function onTimeout() { timerId = null; if (pendingCall === null) return; const { context, args } = pendingCall; pendingCall = null; func.apply(context, args); } return function debounced(...args) { const shouldRunNow = leading && timerId === null; if (timerId !== null) { clearTimeout(timerId); } if (!leading) { pendingCall = { context: this, args }; } timerId = setTimeout(onTimeout, wait); if (shouldRunNow) { func.apply(this, args); } }; }Complete solution
Here is the complete Python file including
FakeTimersanddebounce:from typing import Any, Callable, Dict, Optional, Tuple class FakeTimers: """A fake event loop: virtual time in milliseconds plus setTimeout-style timers. It stands in for JavaScript's setTimeout / clearTimeout (or Jest's fake timers), so debounce can be tested without real waiting. """ def __init__(self) -> None: self.now = 0 self._next_id = 1 # _timers: dict mapping timer_id -> (due_time_ms, zero_arg_callback) self._timers: Dict[int, Tuple[int, Callable[[], Any]]] = {} def set_timeout(self, callback: Callable[[], Any], delay: int) -> int: """Schedule callback() to run delay ms from now; return a timer id.""" timer_id = self._next_id self._next_id += 1 self._timers[timer_id] = (self.now + delay, callback) return timer_id def clear_timeout(self, timer_id: Optional[int]) -> None: """Cancel a timer that has not run yet. Unknown ids and None are ignored.""" self._timers.pop(timer_id, None) def advance(self, ms: int) -> None: """Let ms pass, running each timer that comes due: earliest first, ties in scheduling order.""" target = self.now + ms while True: timer_id = self._earliest_due(target) if timer_id is None: break due, callback = self._timers.pop(timer_id) self.now = due callback() self.now = target def _earliest_due(self, limit: int) -> Optional[int]: """Return the pending timer_id with smallest (due_time, timer_id) <= limit.""" best_id: Optional[int] = None for timer_id, (due, _callback) in self._timers.items(): if due > limit: continue if best_id is None: best_id = timer_id else: best_due = self._timers[best_id][0] # Break due-time ties by smaller timer_id (FIFO scheduling order) if (due, timer_id) < (best_due, best_id): best_id = timer_id return best_id def debounce(func: Callable[..., Any], wait: int, timers: FakeTimers, leading: bool = False) -> Callable[..., None]: """Return a debounced wrapper of func, timed with timers.set_timeout / clear_timeout. A burst is a run of calls in which each call comes less than `wait` ms after the previous one; every call restarts the wait. - leading=False (default): func runs once, `wait` ms after the last call of a burst, with that call's positional and keyword arguments. - leading=True: func runs immediately on the first call of a burst; the other calls of the burst are ignored and there is no trailing run. The wrapper returns None. Raise ValueError if wait < 0. """ if wait < 0: raise ValueError("wait must be non-negative") # timer_id: active timer ID ending the current burst, or None when idle timer_id: Optional[int] = None # pending_call: (args, kwargs) of the latest call waiting for trailing execution pending_call: Optional[Tuple[Tuple[Any, ...], Dict[str, Any]]] = None def on_timeout() -> None: nonlocal timer_id, pending_call # Reset burst state BEFORE invoking func so a re-entrant call inside func # starts a clean new burst instead of having its state overwritten. timer_id = None if pending_call is None: # In leading mode, pending_call stays None: timeout simply ends cooldown return saved_args, saved_kwargs = pending_call pending_call = None func(*saved_args, **saved_kwargs) def debounced(*args: Any, **kwargs: Any) -> None: nonlocal timer_id, pending_call # Phase 1: check leading-edge eligibility BEFORE updating timer_id should_run_now = leading and (timer_id is None) # Phase 2: cancel any in-flight timer so every call restarts the wait window if timer_id is not None: timers.clear_timeout(timer_id) # Phase 3: store latest arguments for trailing mode, and schedule new timer # BEFORE calling func so a synchronous nested call sees timer_id != None if not leading: pending_call = (args, kwargs) timer_id = timers.set_timeout(on_timeout, wait) # Phase 4: fire immediately on the first call of a burst when leading=True if should_run_now: func(*args, **kwargs) return debounced✅ Submit now — all tests should pass.
Intuition & how it works
Think of an automatic elevator door for trailing debounce (leading=False): every time a person walks through the doorway, the 3-second closing countdown resets to zero, so the door closes only after 3 uninterrupted seconds of nobody entering. For leading debounce (leading=True), picture a camera shutter button with a bounce-guard cooldown: pressing it takes a photo immediately on the very first press, and every extra rattle of your finger within the next wait milliseconds resets the cooldown timer without snapping duplicate photos until you stop pressing completely for wait ms. Under the hood, debounce uses a closure (an inner function that retains private access to variables created in its enclosing debounce call) holding just two variables: timer_id (whether a burst is currently active) and pending_call (the latest arguments saved for a trailing run).
Without debouncing, attaching an API call or expensive layout pass directly to a keystroke or scroll handler fires dozens of redundant executions per second. A naive attempt that sets a boolean is_waiting = True without cancelling previous timers fails because earlier timers remain queued in the event loop (the single-threaded scheduler that runs timer and UI callbacks one by one), firing prematurely mid-burst or forgetting to reset after the burst ends.
Walk through three calls—"py" at 0 ms, "python" at 150 ms, and "rust" at 600 ms—with wait = 250 ms:
leading=False:"py"at0 msschedules timer #1 for250 mswith"py"."python"at150 mscancels timer #1, updatespending_callto"python", and schedules timer #2 for400 ms. At400 ms,func("python")runs ("py"never ran)."rust"at600 msstarts a new burst and runsfunc("rust")at850 ms.leading=True:"py"at0 msseestimer_id is None, schedules timer #1 for250 ms, and runsfunc("py")immediately."python"at150 mssees an active timer, cancels timer #1, extends the cooldown timer to400 ms, and ignores"python". At400 ms,timer_idresets toNone."rust"at600 msseestimer_id is Noneand runsfunc("rust")immediately.
Complexity
- Time per wrapper call: O(1), because each call updates two closure variables and performs one
clear_timeoutplus oneset_timeoutdictionary operation on the timer scheduler. (InFakeTimers, advancing virtual time scanspcurrently active timers per firing, where a single debounced wrapper keeps at mostp = 1timer alive at any moment.) - Space per wrapper: O(1) beyond the size of the single latest
(args, kwargs)tuple, because cancelling the previous timer on every call ensures rapid bursts never accumulate queued timers in memory.
Edge cases
wait == 0: behaves likesetTimeout(fn, 0), grouping calls made inside the same synchronous block of code. In trailing mode,debounced("a"); debounced("b")runs onlyfunc("b")once the event loop ticks (advance(0)); in leading mode,"a"runs immediately and"b"is ignored until that0 mstimer fires.- Call arriving at exactly
t_prev + wait: the previous timer expires att_prev + waitright before the new call runs, resettingtimer_idtoNone, so the new call cleanly starts a separate burst. - Re-entrant calls (
funccallingdebouncedinside itself): in trailing mode, clearingtimer_idandpending_callbefore callingfunclets the nested call schedule a fresh burst without being overwritten; in leading mode, schedulingset_timeoutbefore callingfuncensures the synchronous nested call seestimer_id is not Noneand does not double-fire. funcraising an exception: because state updates (timer_id,pending_call) happen beforefunc(*args, **kwargs)is invoked, an exception insidefuncnever leaves the wrapper permanently stuck in a broken state.- Multiple independent wrappers: each
debounce(func, ...)call allocates its own closure scope, so two wrappers around the samefuncnever cancel each other's timers. - Wrapping shared prototype or class methods: attaching a single
debounce(...)wrapper to a JavaScript prototype (Widget.prototype.save = debounce(...)) shares onetimer_idacross everyWidgetinstance, causingwidget2.save()to cancelwidget1.save(). Always create a separate debounced wrapper per object instance in__init__/constructor.
Common mistakes
- Forgetting
clear_timeout(timer_id)beforeset_timeout. Every call leaves an active timer behind, turningdebounceinto a simple fixed delay that still runsfunconce per call. - Checking
timer_id is Noneafter callingset_timeout. At that linetimer_idis already an integer ID, soleading=Truenever fires. - Calling
funcbeforeset_timeoutin leading mode. Iffuncsynchronously invokes the debounced wrapper again,timer_idis stillNone, causing immediate double execution (or infinite recursion) and leaking an uncancelled timer. - Resetting
timer_id = Noneorpending_call = Noneafterfunc(...)insideon_timeout. Any nested wrapper call triggered byfuncgets its newly scheduled timer ID and arguments erased ason_timeoutexits. - Keeping the first call's arguments instead of overwriting
pending_callon each call. Trailing debounce must pass the latest call's arguments—crucial when debouncing an input box where"h","he","hel","help"must search for"help", not"h". - Using an arrow function for the returned wrapper in JavaScript (or dropping
**kwargsin Python). In JavaScript,(...args) =>captures lexicalthisinstead of the caller's object receiver; usefunction(...args)withfunc.apply(this, args). - Calling
debounce(fn, 300)inside a UI render function. That creates a brand-new closure withtimer_id = Noneon every render, defeating debouncing completely. - Confusing debounce with throttle. Debounce waits for
waitms of silence before ending a burst; throttle enforces at most one execution everywaitms even while calls arrive continuously without a pause.
Alternative approaches
- Single-timer timestamp rescheduling (Lodash style): store
last_call_time = clock()on each wrapper call without callingclearTimeout/setTimeoutevery time; when the single active timer wakes up, checkremaining = wait - (clock() - last_call_time)and either firefunc(ifremaining <= 0) or reschedule once forremainingms. This avoids thousands of timer cancellations per second during ultra-high-frequency events likemousemove. - Production Python concurrency primitives: in an
asyncioservice, replaceFakeTimerswithloop.call_later(wait / 1000, on_timeout)andhandle.cancel()(which runs single-threaded on the event loop just like JavaScript). Withthreading.Timer, callbacks run on separate OS threads, so you must also guardtimer_idandpending_callwith athreading.Lockand a monotonic generation counter so an already-awakened timer thread cannot race with a new call.
Follow-up questions
- How can you expose a cancel() method on the debounced wrapper to abort an in-flight burst? Define an inner
cancel()function insidedebouncethat sharesnonlocal timer_id, pending_call: iftimer_id is not None, calltimers.clear_timeout(timer_id), then set bothtimer_id = Noneandpending_call = None. Attach it as an attribute on the wrapper (debounced.cancel = cancel) before returningdebounced. Callingdebounced.cancel()during a burst prevents any pending trailing execution and immediately resets the leading-edge cooldown so the next call starts a fresh burst (and a companionflush()method can runon_timeout()immediately ifpending_call is not None). - How would you extend debounce with a max_wait ceiling so non-stop calls cannot postpone execution indefinitely? Without
max_wait, calling a100 msdebounced function every50 mspostpones execution forever. To bound the delay, keep a second timer IDmax_timer_idscheduled formax_waitms on the first call of a burst (if max_timer_id is None: max_timer_id = timers.set_timeout(on_max_wait, max_wait)) and do not cancel or restartmax_timer_idon subsequent calls in the burst. Whichever timer fires first—waitms of silence (on_timeout) ormax_waitms since burst start (on_max_wait)—clears the other timer, invokesfuncwith the latestpending_callarguments, and resets burst state (or starts a freshmax_waitwindow if calls keep coming). - What testing strategy verifies exact timing and prevents stray executions under rapid call floods? Always inject deterministic virtual timers (
FakeTimersin Python,jest.useFakeTimers()+jest.advanceTimersByTime()in JavaScript) rather than realsleepcalls, which are slow and flaky on loaded CI machines. Test exact millisecond boundaries (wait - 1ms produces0trailing runs; advancing1more ms produces1run with the final call's arguments), then simulate a high-frequency flood such as10,000calls spaced1 msapart withwait = 100 ms—verifying0runs during the9,999 msstorm, exactly1run at10,099 ms, and0leftover timers inFakeTimers._timersafterward. Finally, cross-check hundreds of randomized call-timestamp sequences against a stateless gap-based oracle (times[i + 1] - times[i] >= wait) to catch subtle off-by-one or re-entrancy bugs.
Follow-up questions
- How can you expose a cancel() method on the debounced wrapper to abort an in-flight burst?
- How would you extend debounce with a max_wait ceiling so non-stop calls cannot postpone execution indefinitely?
- What testing strategy verifies exact timing and prevents stray executions under rapid call floods?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array