Skip to content

Instantly share code, notes, and snippets.

@ayanamist
Created December 29, 2014 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayanamist/a15f2cc92a12ce212852 to your computer and use it in GitHub Desktop.
Save ayanamist/a15f2cc92a12ce212852 to your computer and use it in GitHub Desktop.
throttle function for node.js
/**
* 限制fn同时执行的个数,fn必须符合node函数规范,即参数最后一位是回调函数
* 如果有this绑定需求,需要提前bind好,否则this会变null。
*
* @param fn
* @param concurrency
* @returns {Function}
*/
function throttle(fn, concurrency) {
if (concurrency <= 0) {
throw new Error("concurrency must large than zero");
}
var queue = [];
var cnt = concurrency;
function callFn(args) {
var cb = args[args.length - 1];
var argsWithNewCallback = Array.prototype.slice.call(args, 0, args.length - 1);
argsWithNewCallback.push(function newCb() {
var cbArgs = arguments;
process.nextTick(function () {
cb.apply(null, cbArgs);
});
cnt++;
if (queue.length > 0) {
var queuedArgs = queue.shift();
cnt--;
callFn(queuedArgs);
}
});
fn.apply(null, argsWithNewCallback);
}
return function newFn() {
if (cnt > 0) {
cnt--;
callFn(arguments);
} else {
queue.push(arguments);
}
};
}
module.exports = throttle;
if (!module.parent) {
// 一段简单的自测试代码
var echoThrottled = throttle(function echo(content, cb) {
setTimeout(function () {
console.log(content);
cb(content);
}, 1000);
}, 2);
for (var i = 0; i < 10; i++) {
echoThrottled(i, function cb(i) {
echoThrottled(i, cb);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment