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

Debounce

Difficulty: Medium


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.


Code Solutions

function debounce(fn, t) {
    let timer;
    let lastArgs;

    return function(...args) {
        lastArgs = args; // Store the last arguments
        clearTimeout(timer); // Clear the previous timer
        timer = setTimeout(() => {
            fn(...lastArgs); // Call the function with the last arguments
        }, t);
    };
}
← Back to All Questions