-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (48 loc) · 957 Bytes
/
index.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
55
56
57
var Promise = require("bluebird");
function st(time, cb){
return setTimeout(cb, time);
}
var stp = Promise.promisify(st);
function throttler(delay){
const DELAY = delay;
var last_request = -Infinity;
var queue = [];
function delta(){
return Date.now() - last_request;
}
function update_ts(){
last_request = Date.now();
}
function add_to_queue(fn){
return new Promise(function(resolve, reject){
var qf = function(){
Promise.resolve(fn()).then(function(result){
resolve(result);
update_ts();
}).catch(reject);
};
queue.push(qf);
});
}
function clear_queue(){
if(queue.length && delta() >= DELAY){
var qf = queue.shift();
qf();
update_ts();
}
if(queue.length){
setTimeout(clear_queue, DELAY);
}
}
return function(fn){
if(delta() < DELAY ){
var p = add_to_queue(fn);
clear_queue();
return p;
} else {
update_ts();
return fn();
}
};
}
module.exports = throttler;