setTimeout from a web worker

醉酒当歌 提交于 2019-12-10 15:59:51

问题


What if I want to put a web worker on pause if I cannot proceed processing data, and try a second later? Can I do that in this manner inside a web worker?

var doStuff = function() {
    if( databaseBusy() ) {
        setTimeout(doStuff, 1000);
    } else {
        doStuffIndeed();
    }
}

I'm getting Uncaught RangeError: Maximum call stack size exceeded and something tells me it's because of the code above.


回答1:


If by "pause" you mean "further calls to worker.postMessage() will get queued up and not processed by the worker", then no, you cannot use setTimeout() for this. setTimeout() is not a busywait, but rather an in-thread mechanism for delaying work until a later scheduled time. The web worker will still receive a new onmessage event from the main queue as soon as it is posted.

What you can do, however, is queue them up manually and use setTimeout to try to process them later. For example:

worker.js

var workQueue = [];
addEventListener('message',function(evt){
  workQueue.push(evt.data);
  doStuff();
},false);

function doStuff(){
  while (!databaseBusy()) doStuffIndeed(workQueue.shift());
  if (workQueue.length) setTimeout(doStuff,1000);
}
  • Each time a message is received the worker puts it into a queue and calls tryToProcess.
  • tryToProcess pulls messages from the queue one at a time as long as the database is available.
  • If the database isn't available and there are messages left, it tries again in 1 second.


来源:https://stackoverflow.com/questions/22043120/settimeout-from-a-web-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!