🔗LC2627 🟡 Medium 🧩 Pattern – Promises and Timeout
📅 Day 18/30 Days of JavaScript
Given a function fn
and a time in milliseconds t
, return a debounced version of that function.
A 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 30ms
, 60ms
, 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
.
Example
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 1 st call is cancelled by the 2n d call because the 2n d call occurred before 100 ms
The 2n d call is delayed by 50 ms and executed at 125 ms.The inputs were(2).
Solution
/**
* @param {Function} fn
* @param {number} t milliseconds
* @return {Function}
*/
var debounce = function(fn, t) {
let timerId;
return function(...args) {
if(timerId){
// Clear existing timer and fn call
clearTimeout(timerId);
}
// call fn with args as params after time t
timerId = setTimeout(fn, t, ...args)
}
};
/**
* const log = debounce(console.log, 100);
* log('Hello'); // cancelled
* log('Hello'); // cancelled
* log('Hello'); // Logged at t=100ms
*/