admin管理员组

文章数量:1332395

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.

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.

Share Improve this question asked Feb 26, 2014 at 13:38 Misha SlyusarevMisha Slyusarev 1,3833 gold badges19 silver badges48 bronze badges 5
  • Why not use setInterval() instead if you want it to repeat? – Lloyd Commented Feb 26, 2014 at 13:40
  • I'd like to stop it when the database stop being busy. – Misha Slyusarev Commented Feb 26, 2014 at 13:41
  • 1 @MishaSlyusarev Then use clearInterval() after your condition is met. – Sirko Commented Feb 26, 2014 at 13:43
  • 1 Are you sure the problem is the timeout for the stack size? Are you using any recursion in the webworker code? – MarcoL Commented Feb 26, 2014 at 13:46
  • Not sure that's the case, just wanted to figure out the proper way of using setTimeout from web workers. – Misha Slyusarev Commented Feb 26, 2014 at 13:51
Add a ment  | 

1 Answer 1

Reset to default 4

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.

本文标签: javascriptsetTimeout from a web workerStack Overflow