Skip to content

Instantly share code, notes, and snippets.

@arfeo
Last active February 2, 2018 21:54
Show Gist options
  • Save arfeo/6f89f1e9a88469124dc3679da597f4d0 to your computer and use it in GitHub Desktop.
Save arfeo/6f89f1e9a88469124dc3679da597f4d0 to your computer and use it in GitHub Desktop.
[ES6] Function call limiter (times per second)
/**
*
* Функция ограничения вызова функции (не чаще некоторого кол-ва раз в секунду)
*
* @param {Integer} count Кол-во выполняемых в 1 секунду вызовов
*
* ---
*
* Пример использования:
*
* foo.callLimit(1)
*
*/
Function.prototype.callLimit = function(count) {
const fn = this;
let exp = 0;
let timer;
return () => {
const el = exp - new Date();
if(el <= 0) {
timer = clearTimeout(timer);
fn.apply(this, arguments);
exp = Number(new Date()) + parseInt(1000 / count);
} else {
if(!timer) {
const args = arguments;
const scope = this;
timer = setTimeout(() => {
exp = 0;
args.callee.apply(scope, args);
}, el);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment