problems(js): add “2627. Debounce”

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2023-05-19 14:47:50 +02:00
parent 6ca5f53327
commit b573899153
Signed by: mfocko
GPG key ID: 7C47D46246790496

22
problems/debounce.js Normal file
View file

@ -0,0 +1,22 @@
/**
* @param {Function} fn
* @param {number} t milliseconds
* @return {Function}
*/
var debounce = function(fn, t) {
let timeout = null;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
fn(...args);
}, t);
}
};
/**
* const log = debounce(console.log, 100);
* log('Hello'); // cancelled
* log('Hello'); // cancelled
* log('Hello'); // Logged at t=100ms
*/