Last active
July 24, 2020 07:45
-
-
Save sematgt/cdd5e04e375a0e8c99d6e26148fbaebb to your computer and use it in GitHub Desktop.
throttling decorator js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function throttle(f, ms) { | |
return function updater() { | |
if (updater.ready === false) { | |
updater.args = arguments; | |
return; | |
} | |
updater.ready = false; | |
f.apply(this, arguments); | |
setTimeout(() => { | |
updater.ready = true; | |
if (updater.args) { | |
f.apply(this, updater.args); | |
} | |
}, ms) | |
} | |
} | |
function f(message = 'hello') { | |
console.log(message); | |
} | |
let f1000 = throttle(f, 1000); | |
f1000(1); // показывает 1 | |
f1000(2); // (ограничение, 1000 мс ещё нет) | |
f1000(3); // (ограничение, 1000 мс ещё нет) | |
// когда 1000 мс истекли ... | |
// ...выводим 3, промежуточное значение 2 было проигнорировано |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment