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.