
Sponsored
Sponsored
This approach involves using a timeout mechanism to delay the execution of the function by t milliseconds. If the function is called again within this delay period, the existing delay is cancelled and a new delay is started. This ensures that the function execution occurs only after the last call within the time window has passed.
Time Complexity: O(1) per function call as we only set and clear timeouts.
Space Complexity: O(1) as we are only storing the timer id.
1function debounce(fn, t) {
2 let timer;
3
The JavaScript implementation utilizes the setTimeout function to delay execution of fn by t milliseconds. If fn is called again before this delay expires, clearTimeout is used to cancel the previous delay and initiate a new one. This ensures that only the last call within the debounce window is eventually executed.
This approach takes advantage of closures to maintain the state of the timeout. This allows us to track whether a timeout is active and reset it if needed. This encapsulation within the closure ensures that each debounced function call properly manages the delay on its own.
Time Complexity: O(1) per function call because managing a single timeout involves constant-time operations.
Space Complexity: O(1) due to the single timerId variable maintained per debounced instance.
1function debounce(fn, t) {
2 let timerId;
3 return function(...args) {
4 if (timerId) {
5 clearTimeout(timerId);
6 }
7 timerId = setTimeout(() => {
8 fn(...args);
9 }, t);
10 };
11}
12
13// Example Usage
14let start = Date.now();
15function log(...inputs) {
16 console.log([Date.now() - start, inputs])
17}
18const dlog = debounce(log, 50);
19setTimeout(() => dlog(1), 50);
20setTimeout(() => dlog(2), 75);
21In this JavaScript solution, a closure is created around a timerId variable that keeps track of the current timeout. Each invocation of the debounced function checks this variable; if a timeout is active, it is cleared before setting a new one. This method leverages closures to effectively manage state across function invocations.