Taro Logo

Debounce

Medium
a month ago

Given a function fn and a time in milliseconds t, return a debounced version of that function.

debounced function is a function 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.

For example, let's say t = 50ms, and the function was called at 30ms60ms, and 100ms.

The first 2 function calls would be cancelled, and the 3rd function call would be executed at 150ms.

If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms, and the 3rd would be executed at 135ms.

Please solve it without using lodash's _.debounce() function.

Example 1:

Input: 
t = 50
calls = [
  {"t": 50, inputs: [1]},
  {"t": 75, inputs: [2]}
]
Output: [{"t": 125, inputs: [2]}]
Explanation:
let start = Date.now();
function log(...inputs) { 
  console.log([Date.now() - start, inputs ])
}
const dlog = debounce(log, 50);
setTimeout(() => dlog(1), 50);
setTimeout(() => dlog(2), 75);

The 1st call is cancelled by the 2nd call because the 2nd call occurred before 100ms
The 2nd call is delayed by 50ms and executed at 125ms. The inputs were (2).

Example 2:

Input: 
t = 20
calls = [
  {"t": 50, inputs: [1]},
  {"t": 100, inputs: [2]}
]
Output: [{"t": 70, inputs: [1]}, {"t": 120, inputs: [2]}]
Explanation:
The 1st call is delayed until 70ms. The inputs were (1).
The 2nd call is delayed until 120ms. The inputs were (2).

Example 3:

Input: 
t = 150
calls = [
  {"t": 50, inputs: [1, 2]},
  {"t": 300, inputs: [3, 4]},
  {"t": 300, inputs: [5, 6]}
]
Output: [{"t": 200, inputs: [1,2]}, {"t": 450, inputs: [5, 6]}]
Explanation:
The 1st call is delayed by 150ms and ran at 200ms. The inputs were (1, 2).
The 2nd call is cancelled by the 3rd call
The 3rd call is delayed by 150ms and ran at 450ms. The inputs were (5, 6).

Constraints:

  • 0 <= t <= 1000
  • 1 <= calls.length <= 10
  • 0 <= calls[i].t <= 1000
  • 0 <= calls[i].inputs.length <= 10
Sample Answer
/**
 * @param {Function} fn
 * @param {number} t
 * @return {Function}
 */
var debounce = function(fn, t) {
    let timerId;

    return function(...args) {
        // Clear the previous timer if it exists
        if (timerId) {
            clearTimeout(timerId);
        }

        // Set a new timer
        timerId = setTimeout(() => {
            fn.apply(this, args);
        }, t);
    }
};

/**
 * const log = (...args) => console.log(args);
 * const dlog = debounce(log, 50);
 * setTimeout(() => dlog(1), 30);
 * setTimeout(() => dlog(2), 100);
 */

Explanation:

The debounce function takes a function fn and a time t as input and returns a debounced version of the function.

  1. timerId variable: A variable timerId is declared to store the ID of the timer. This variable is used to clear the previous timer if the debounced function is called again within the specified time.
  2. Returned function: The debounce function returns a new function that will be the debounced version of the original function fn. This returned function accepts any number of arguments using the rest parameter syntax ...args.
  3. Clearing the previous timer: Inside the returned function, it checks if there is an existing timer (if (timerId)). If there is, it clears the timer using clearTimeout(timerId). This is important because if the function is called again within the debounce time, we want to cancel the previous execution.
  4. Setting a new timer: A new timer is set using setTimeout. The setTimeout function will execute the original function fn after t milliseconds. The apply method is used to call fn with the correct this context and the arguments passed to the debounced function.

Example:

const log = (...args) => console.log(args);
const dlog = debounce(log, 50);
setTimeout(() => dlog(1), 30);   // Will be cancelled
setTimeout(() => dlog(2), 100);  // Will execute after 50ms, around 150ms

In this example, the first call to dlog at 30ms will be cancelled because the second call to dlog occurs at 100ms, which is within the 50ms debounce time. The second call will be executed after 50ms, around 150ms.

Big O Analysis

Time Complexity: O(1)

The debounce function itself has a time complexity of O(1) because it only performs a few simple operations: clearing a timer (if it exists) and setting a new timer. The time complexity of the original function fn is not considered here because it is only executed once after the debounce time has elapsed.

Space Complexity: O(1)

The debounce function has a space complexity of O(1) because it only uses a few variables to store the timer ID and the function to be debounced. The space complexity of the original function fn is not considered here because it is only stored as a reference.

Edge Cases:

  1. t = 0: If t is 0, the function will be executed immediately after the first call. Subsequent calls will still cancel each other if they occur within the immediate execution time.
  2. Multiple calls within t: If the function is called multiple times within the debounce time t, only the last call will be executed after t milliseconds from the last call.
  3. No calls: If the function is never called, the debounced function will never be executed.