-
Notifications
You must be signed in to change notification settings - Fork 1
/
qthrottle.js
107 lines (73 loc) · 1.67 KB
/
qthrottle.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
var q = require('q');
module.exports = function(limit, progress) {
function QThrottle(limit) {
var queue = [];
var running = 0;
this.fapply = function(fn, thisArg, args) {
var deferred = q.defer();
queue.push({
deferred: deferred,
fn: fn,
thisArg: thisArg,
args: args
});
run();
return deferred.promise;
};
this.fcall = function(fn, thisArg) {
var deferred = q.defer();
queue.push({
deferred: deferred,
fn: fn,
thisArg: thisArg,
args: Array.prototype.slice.call(arguments, 2)
});
run();
return deferred.promise;
};
this.throttlize = function(fns, thisArg) {
var self = this;
var wrap = function(fn, thisArg) {
return function() {
return self.fapply(fn, thisArg, Array.prototype.slice.call(arguments));
};
};
if (Array.isArray(fns)) {
return fns.map(function(fn) {
return wrap(fn, thisArg);
});
}
if (typeof(fns) === 'object') {
Object.keys(fns)
.forEach(function(key) {
fns[key] = wrap(fns[key], thisArg);
});
return fns;
}
throw new Error('Invalid 1st argument type, expected array or object');
};
var run = function() {
if (running < limit && queue.length > 0) {
running++;
if (progress)
progress(running, queue.length);
var job = queue.pop();
job.fn.apply(job.thisArg, job.args)
.then(function(value) {
running--;
job.deferred.resolve(value);
run();
})
.fail(function(error) {
running--;
job.deferred.reject(error);
run();
});
} else {
if (progress)
progress(running, queue.length);
}
};
}
return new QThrottle(limit);
};