Problem Description
Given a function fn
and a time in milliseconds t
, return a debounced version of that function. A debounced function is one whose execution is delayed by t
milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters.
Key Insights
- A debounced function delays execution until after a specified time period has elapsed since the last invocation.
- If the function is called again within the delay period, the previous call is cancelled.
- The function should maintain the parameters from the last valid invocation.
Space and Time Complexity
Time Complexity: O(n), where n is the number of calls to debounce since each call is processed once.
Space Complexity: O(1), as we only store a few variables for managing the timer and parameters.
Solution
To implement the debounce function, we can use a closure to manage the state of the timer and the last arguments passed to the function. When the debounced function is called, we check if there is an existing timer. If there is, we cancel it. We then start a new timer that will call the original function after the specified delay, passing in the last arguments. This way, only the most recent call within the delay period is executed.