Last active
February 2, 2018 21:54
-
-
Save arfeo/6f89f1e9a88469124dc3679da597f4d0 to your computer and use it in GitHub Desktop.
[ES6] Function call limiter (times per second)
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
/** | |
* | |
* Функция ограничения вызова функции (не чаще некоторого кол-ва раз в секунду) | |
* | |
* @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