我有一个队列,我将消息推送到我想继续处理的状态。
我之所以需要一个队列,是因为这些消息来得太快,我无法完成处理!
这是我的代码:
var messageQueue = [];
var ws = ...;
//When I get a socket.io message...
ws.on('message', function(data)
{
//Add it to the queue
addToQueue(data);
});
//Function that adds it to the queue:
function addToQueue(fullMessage)
{
messageQueue.push(fullMessage);
},
//Function that I'd like to run constantly
function fetcher()
{
while (messageQueue.length > 0)
{
//get the next message on the queue
var msg = messageQueue.shift();
handleMessage(msg);
}
//fetcher()?
}
//Function that works with the message
function handleMessage(fullMessage)
{
//do things with the message
}
关于如何获得" fetcher"的任何想法什么时候队列中有项目运行?
每次尝试我都会意外地以递归方式调用它并打破页面:(
答案 0 :(得分:1)
function fetcher()
{
if (messageQueue.length > 0)
{
//get the next message on the queue
var msg = messageQueue.shift();
handleMessage(msg);
}
setTimeout(fetcher);
}