2015-02-11 40 views
0

我有一个队列,可以将消息推送到我想要连续处理的队列中。Javascript:监视队列/连续运行功能

我之所以需要一个队列,是因为消息来得太快,无法完成处理!

这里是我的代码:

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 
    } 

我如何能得到“提取器”运行随时有队列中的项目的任何想法?

每次尝试我做我结束了意外递归调用它,并打破了网页:(

回答

1
function fetcher() 
    { 
     if (messageQueue.length > 0) 
     { 
      //get the next message on the queue 
      var msg = messageQueue.shift(); 
      handleMessage(msg); 
     } 
     setTimeout(fetcher); 

    } 
+0

这会导致递归问题,我得到“最大的调用堆栈大小超出了”错误:/我已经试过“的setTimeout “之前,延迟1秒,但它做了同样的: – Kayvar 2015-02-11 19:33:59

+0

你不应该得到一个递归问题'setTimeout()'是避免这种情况的方法。在你的代码中必须有其他的东西导致它。 – 2015-02-11 19:35:04

+0

因为'setTimeout()'将传递给它的函数添加到一个叫做事件循环的队列中,等待这个调用堆栈为空 – 2015-02-11 19:36:48