We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Debounce

Number: 2743

Difficulty: Medium

Paid? No

Companies: Confluent, Google, Amazon, TikTok


Problem Description

Implement a debounce function that delays the execution of a given function by t milliseconds and cancels any previously scheduled execution if the debounced function is called again within that t-millisecond window. The debounced function should forward all provided arguments to the original function when executed.


Key Insights

  • Each call to the debounced function resets the timer.
  • Only the most recent function call (that isn’t subsequently cancelled) will eventually execute.
  • Passing of parameters is handled by storing the arguments of the latest call.
  • The solution leverages timers (or equivalent scheduling mechanisms) and cancellation techniques.

Space and Time Complexity

Time Complexity: O(1) per call, as each invocation only clears and sets a timer. Space Complexity: O(1), since only a single timer reference is maintained.


Solution

The solution creates a wrapper function that maintains an internal timer reference. On each call to the debounced function, if a timer exists, it is cancelled. A new timer is then set to execute the original function after t milliseconds with the provided arguments. This ensures that only the last invocation runs if multiple calls occur within the delay period.


Code Solutions

import threading

def debounce(fn, t):
    # Timer reference to manage the scheduled execution
    timer = None

    def debounced(*args, **kwargs):
        nonlocal timer
        # Cancel previous timer if it exists
        if timer is not None:
            timer.cancel()
        # Start a new timer (convert milliseconds to seconds)
        timer = threading.Timer(t / 1000.0, lambda: fn(*args, **kwargs))
        timer.start()

    return debounced

# Example usage:
if __name__ == "__main__":
    import time
    start = time.time()

    def log(*args):
        print((time.time() - start, args))

    dlog = debounce(log, 50)
    dlog(1)
    time.sleep(0.025)  # 25ms delay before the next call
    dlog(2)
    time.sleep(0.1)   # Wait to allow the debounced function to execute
← Back to All Questions