-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (58 loc) · 1.31 KB
/
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
function throttle(fn, limit, interval) {
if (!Number.isFinite(limit)) {
throw new TypeError('Expected `limit` to be a finite number');
}
if (!Number.isFinite(interval)) {
throw new TypeError('Expected `interval` to be a finite number');
}
var queue = [];
var timeouts = [];
var activeCount = 0;
var next = function () {
activeCount++;
var id = setTimeout(function () {
activeCount--;
if (queue.length > 0) {
next();
}
timeouts = timeouts.filter(function (currentId) {
return currentId !== id;
});
}, interval);
if (timeouts.indexOf(id) < 0) {
timeouts.push(id);
}
var x = queue.shift();
x.resolve(fn.apply(x.self, x.args));
};
var throttled = function () {
var args = arguments;
var that = this;
return new Promise(function (resolve, reject) {
queue.push({
resolve: resolve,
reject: reject,
args: args,
self: that
});
if (activeCount < limit) {
next();
}
});
};
throttled.abort = function () {
timeouts.forEach(clearTimeout);
timeouts = [];
queue.forEach(function (x) {
x.reject(new throttle.AbortError());
});
queue.length = 0;
};
return throttled;
}
function AbortError() {
Error.call(this, 'Throttled function aborted');
this.name = 'AbortError';
}
throttle.AbortError = AbortError;
module.exports = throttle;