看起来你在这里需要的是一个限制你的函数调用的助手。例如:
var makeThrottler = function() {
var toRun = null, timeout = null;
function doRun() {
if (!toRun) {
// nothing to run; we set timeout to null so that the
// next function to execute knows to run immediately
timeout = null;
return;
}
// set a timeout of 5s before
timeout = setTimeout(function() {
doRun();
}, 5000);
// we need to do this temp thing to protect against
// calling executeThrottled again within toRun
var temp = toRun;
toRun = null;
temp();
}
function executeThrottled(fn) {
// this is the function we want to execute next; it
// overwrites any function we've stored earlier
toRun = fn;
// if we already ran within the last 5 seconds, don't do
// anything now (our function will be called later)
if (timeout)
return;
// execute the function right away
doRun();
}
return executeThrottled;
}
这是一个如何使用它的示例:
var throttled = makeThrottler(), x = 0;
function increment() {
throttled(function() {
console.log(x);
});
x++;
setTimeout(increment, 1000);
}
increment();
增量函数x
每秒增加一。日志记录受到限制,因此您将看到的输出是 0、5、10 等。(它们可能偶尔会因计时不准确而减少 1。)
您的原始代码将变为:
cli_sub.subscribe("tradeupdate");
cli_sub.on("message",function(channel,message) {
throttled(function() {
io.sockets.emit('ablv', message);
});
});