UNPKG

1.08 kBJavaScriptView Raw
1"use strict";
2
3var defaultMaxRunning = 50;
4
5var limit = module.exports = function (func, maxRunning) {
6 var running = 0;
7 var queue = [];
8 if (!maxRunning) maxRunning = defaultMaxRunning;
9 return function limited() {
10 var self = this;
11 var args = Array.prototype.slice.call(arguments);
12 if (running >= maxRunning) {
13 queue.push(args);
14 return;
15 }
16 var cb = typeof args[args.length - 1] === 'function' && args.pop();
17 ++running;
18 args.push(function () {
19 var cbargs = arguments;
20 --running;
21 cb && process.nextTick(function () {
22 cb.apply(self, cbargs);
23 });
24 if (queue.length) {
25 var next = queue.shift();
26 limited.apply(self, next);
27 }
28 });
29 func.apply(self, args);
30 };
31};
32
33module.exports.method = function (classOrObj, method, maxRunning) {
34 if (typeof classOrObj === 'function') {
35 var func = classOrObj.prototype[method];
36 classOrObj.prototype[method] = limit(func, maxRunning);
37 } else {
38 var func = classOrObj[method];
39 classOrObj[method] = limit(func, maxRunning);
40 }
41};
\No newline at end of file