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()
Solution 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);
functiondoStuff(){
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.
Post a Comment for "Settimeout From A Web Worker"