Skip to content

Instantly share code, notes, and snippets.

@sematgt
Last active July 24, 2020 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sematgt/cdd5e04e375a0e8c99d6e26148fbaebb to your computer and use it in GitHub Desktop.
Save sematgt/cdd5e04e375a0e8c99d6e26148fbaebb to your computer and use it in GitHub Desktop.
throttling decorator js
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