problems(js): add “2627. Debounce”
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
6ca5f53327
commit
b573899153
1 changed files with 22 additions and 0 deletions
22
problems/debounce.js
Normal file
22
problems/debounce.js
Normal 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
|
||||||
|
*/
|
Loading…
Reference in a new issue