简体   繁体   中英

setTimeout from a web worker

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM