forked from schroffl/teamspeak-query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttle.js
54 lines (42 loc) · 1.02 KB
/
throttle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict';
/**
* Throttles function calls if needed.
*
* @class Throttle
*/
class Throttle extends Map {
constructor(config) {
super([
[ 'max', 10 ],
[ 'per', 1000 ],
[ 'enable', true ]
]);
for(let prop in config)
this.set(prop, config[prop]);
this.calls = 0;
this.stack = [ ];
setInterval(() => {
this.calls -= this.calls - 1 >= 0 ? 1 : 0;
if(this.get('enable') && this.calls > 1 || !this.stack.length)
return;
let numLeft = this.get('max') - this.calls,
chunk = this.stack.slice(0, numLeft);
this.stack = this.stack.slice(numLeft)
chunk.forEach(this.run.bind(this));
}, this.get('per') / this.get('max'));
}
/**
* Run a function that will be throttled if needed
*
* @param {Function} fn The function
*/
run(fn) {
if(this.calls < this.get('max')) {
if(this.get('enable'))
this.calls++;
fn();
} else
this.stack.push(fn);
}
}
module.exports = Throttle;