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): func executes once per burst, exactly wait milliseconds 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): func executes immediately on the first call of a burst with that call's *args and **kwargs. Every subsequent call arriving before wait quiet milliseconds have elapsed resets the wait-millisecond cooldown and is otherwise ignored (no trailing execution occurs when the cooldown ends).
  • Bound methods passed as func must retain their bound object instance, the wrapper always returns None, and independent calls to debounce must not share state.
  • Raise ValueError if wait < 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

  • wait is an integer (wait >= 0 is valid, including wait == 0; wait < 0 raises ValueError).
  • Each call to the debounced wrapper must execute in O(1) time and maintain O(1) pending timers per wrapper, even under rapid bursts of thousands of calls.
  • Re-entrant calls made inside func must 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

  1. 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 to func.

    In starter.py, timer scheduling is modeled deterministically with FakeTimers (standing in for JavaScript's setTimeout / clearTimeout or an event-loop scheduler):

    • timers.set_timeout(callback, delay) and timers.clear_timeout(timer_id) schedule and cancel callbacks on a virtual millisecond clock (timers.now), advancing via timers.advance(ms) without sleeping in real wall-clock time.
    • *args, **kwargs and bound methods: in Python, passing a bound method like account.save already carries its receiver instance inside the callable object, and *args, **kwargs forwards all positional and keyword arguments intact.
    • Validation: leading defaults to False, and wait < 0 raises ValueError.
  2. 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 wait milliseconds. Crucially, every call resets the wait-millisecond countdown, so a burst ends only after wait full milliseconds of silence.

    Suppose wait = 250 ms and a user calls the wrapper at t = 0, 100, and 220 ms:

    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 separate trailing flag that defaults to true; worth noting aloud in an interview).
    • Leading mode still extends the quiet window on every call: if calls arrive at 0, 180, and 400 ms with wait = 300, "req-2" and "req-3" keep pushing the cooldown out to 700 ms. Only after 300 ms of complete silence does the next call start a new burst (unlike throttling, which fires on a fixed periodic schedule during non-stop input).
  3. 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 outer debounce call even after debounce returns), 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, or None when no burst is in progress.
    • pending_call: a (args, kwargs) tuple holding the latest call's arguments when leading=False, or None when 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 = None
    
  4. Code the timeout callback and protect re-entrant calls

    When wait ms of silence finally pass, on_timeout() runs. Its job is to mark the burst finished (timer_id = None) and, in trailing mode, run func with the saved latest arguments.

    Pay close attention to the order of lines inside on_timeout(): we reset timer_id = None and pending_call = None before calling func(*saved_args, **saved_kwargs). Why? Suppose func itself calls the debounced wrapper again (for example, saving a draft triggers a follow-up state update). If we cleared timer_id and pending_call after func returned, we would accidentally wipe out the brand-new timer and arguments that func just 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)
    
  5. Code the wrapper for both trailing and leading edges

    Inside debounced(*args, **kwargs), four small steps run in a deliberate order:

    1. Check leading eligibility first: should_run_now = leading and (timer_id is None). We must compute this before scheduling the new timer, because afterward timer_id is never None.
    2. Cancel the previous timer: if timer_id is not None, call timers.clear_timeout(timer_id) so earlier calls in the burst never fire early.
    3. Save arguments and schedule the fresh timer: in trailing mode, overwrite pending_call = (args, kwargs) so the latest arguments win; in both modes, schedule timer_id = timers.set_timeout(on_timeout, wait).
    4. Run func last if should_run_now: scheduling the timer before calling func guarantees that if func synchronously calls debounced(...) again (or raises an exception), timer_id is 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
    
  6. 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)
    
  7. 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 dynamic this from the call site (obj.method() sets this === obj), and invoke func.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);
        }
      };
    }
    
  8. Complete solution

    Here is the complete Python file including FakeTimers and debounce:

    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" at 0 ms schedules timer #1 for 250 ms with "py". "python" at 150 ms cancels timer #1, updates pending_call to "python", and schedules timer #2 for 400 ms. At 400 ms, func("python") runs ("py" never ran). "rust" at 600 ms starts a new burst and runs func("rust") at 850 ms.
  • leading=True: "py" at 0 ms sees timer_id is None, schedules timer #1 for 250 ms, and runs func("py") immediately. "python" at 150 ms sees an active timer, cancels timer #1, extends the cooldown timer to 400 ms, and ignores "python". At 400 ms, timer_id resets to None. "rust" at 600 ms sees timer_id is None and runs func("rust") immediately.

Complexity

  • Time per wrapper call: O(1), because each call updates two closure variables and performs one clear_timeout plus one set_timeout dictionary operation on the timer scheduler. (In FakeTimers, advancing virtual time scans p currently active timers per firing, where a single debounced wrapper keeps at most p = 1 timer 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 like setTimeout(fn, 0), grouping calls made inside the same synchronous block of code. In trailing mode, debounced("a"); debounced("b") runs only func("b") once the event loop ticks (advance(0)); in leading mode, "a" runs immediately and "b" is ignored until that 0 ms timer fires.
  • Call arriving at exactly t_prev + wait: the previous timer expires at t_prev + wait right before the new call runs, resetting timer_id to None, so the new call cleanly starts a separate burst.
  • Re-entrant calls (func calling debounced inside itself): in trailing mode, clearing timer_id and pending_call before calling func lets the nested call schedule a fresh burst without being overwritten; in leading mode, scheduling set_timeout before calling func ensures the synchronous nested call sees timer_id is not None and does not double-fire.
  • func raising an exception: because state updates (timer_id, pending_call) happen before func(*args, **kwargs) is invoked, an exception inside func never 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 same func never 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 one timer_id across every Widget instance, causing widget2.save() to cancel widget1.save(). Always create a separate debounced wrapper per object instance in __init__ / constructor.

Common mistakes

  • Forgetting clear_timeout(timer_id) before set_timeout. Every call leaves an active timer behind, turning debounce into a simple fixed delay that still runs func once per call.
  • Checking timer_id is None after calling set_timeout. At that line timer_id is already an integer ID, so leading=True never fires.
  • Calling func before set_timeout in leading mode. If func synchronously invokes the debounced wrapper again, timer_id is still None, causing immediate double execution (or infinite recursion) and leaking an uncancelled timer.
  • Resetting timer_id = None or pending_call = None after func(...) inside on_timeout. Any nested wrapper call triggered by func gets its newly scheduled timer ID and arguments erased as on_timeout exits.
  • Keeping the first call's arguments instead of overwriting pending_call on 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 **kwargs in Python). In JavaScript, (...args) => captures lexical this instead of the caller's object receiver; use function(...args) with func.apply(this, args).
  • Calling debounce(fn, 300) inside a UI render function. That creates a brand-new closure with timer_id = None on every render, defeating debouncing completely.
  • Confusing debounce with throttle. Debounce waits for wait ms of silence before ending a burst; throttle enforces at most one execution every wait ms 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 calling clearTimeout/setTimeout every time; when the single active timer wakes up, check remaining = wait - (clock() - last_call_time) and either fire func (if remaining <= 0) or reschedule once for remaining ms. This avoids thousands of timer cancellations per second during ultra-high-frequency events like mousemove.
  • Production Python concurrency primitives: in an asyncio service, replace FakeTimers with loop.call_later(wait / 1000, on_timeout) and handle.cancel() (which runs single-threaded on the event loop just like JavaScript). With threading.Timer, callbacks run on separate OS threads, so you must also guard timer_id and pending_call with a threading.Lock and 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 inside debounce that shares nonlocal timer_id, pending_call: if timer_id is not None, call timers.clear_timeout(timer_id), then set both timer_id = None and pending_call = None. Attach it as an attribute on the wrapper (debounced.cancel = cancel) before returning debounced. Calling debounced.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 companion flush() method can run on_timeout() immediately if pending_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 a 100 ms debounced function every 50 ms postpones execution forever. To bound the delay, keep a second timer ID max_timer_id scheduled for max_wait ms 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 restart max_timer_id on subsequent calls in the burst. Whichever timer fires first—wait ms of silence (on_timeout) or max_wait ms since burst start (on_max_wait)—clears the other timer, invokes func with the latest pending_call arguments, and resets burst state (or starts a fresh max_wait window if calls keep coming).
  • What testing strategy verifies exact timing and prevents stray executions under rapid call floods? Always inject deterministic virtual timers (FakeTimers in Python, jest.useFakeTimers() + jest.advanceTimersByTime() in JavaScript) rather than real sleep calls, which are slow and flaky on loaded CI machines. Test exact millisecond boundaries (wait - 1 ms produces 0 trailing runs; advancing 1 more ms produces 1 run with the final call's arguments), then simulate a high-frequency flood such as 10,000 calls spaced 1 ms apart with wait = 100 ms—verifying 0 runs during the 9,999 ms storm, exactly 1 run at 10,099 ms, and 0 leftover timers in FakeTimers._timers afterward. 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

Similar questions

More Grayswan Ai interview questions

All 1 Grayswan Ai questions →