编辑 2: Underscore 已经实现了类似的功能,请查看 throttle function。
编辑:我用下面的代码制作了一个模块,请访问:https://github.com/gammasoft/rate-limited
这是一个非常简单的实现,可能会对您有所帮助。
参数:
1.params:包含要通过 SES 发送的电子邮件地址的数组
2.fn:一次发送一封电子邮件的功能
3. timeout:每次调用fn 之间的最短时间,以毫秒为单位,例如:100 封电子邮件/秒然后您通过1000/100(1 秒除以 100 封电子邮件)
4.callback:一切结束时调用的函数
代码
// rate-limit.js
var async = require("async");
module.exports = function(params, fn, timeout, callback){
var length = params.length;
var wait = function(cb){
if(--length === 0) return cb();
else setTimeout(function(){
cb();
}, timeout);
};
async.eachSeries(params, async.compose(wait, fn), function(err){
callback(err);
});
};
module.exports.timesPerSecond = function(times){
if(times === 0) throw new Error("Should not be zero");
return 1000/times;
};
module.exports.timesPerMinute = function(times){
if(times === 0) throw new Error("Should not be zero");
return (60 * 1000)/times;
};
用法
//test.js
var rateLimited = require("./rate-limit.js");
var timesPerMinute = rateLimited.timesPerMinute;
console.time("time");
rateLimited([1, 2, 3, 4, 5, 6], function(name, cb){
console.log(name);
cb();
}, timesPerMinute(5), function(err){
if(err) throw err;
console.timeEnd("time");
});