I have a Dedicated Webworker that upon receiving a starting signal goes into a long loop and based on some startup settings the loop would "yield" at given points of execution.
This is a simplified version of my code
var mode = null;
var generator = null;
function* loop() {
for(var i=0;i<10000;i++) {
//Do stuff
for(var j=0;j<10000;j++) {
//Do stuff
if( mode == 'inner' ){
//Yield after each inner loop iteration
yield 2;
}
}
if( mode == 'outer' ){
//Yield after each outer loop iteration
yield 1;
}
}
/*
If mode is not inner or outer the function won't yield
and will process the whole loop in one shot
*/
return null;
}
generator = loop();
self.onmessage = function(event) {
var m = event.data;
if(m.operation == 'run') {
mode = m.mode;
generator.next();
}
if(m.operation == 'pause') {
//Set a flag and check for it in the loop
}
}
What I want to do is to allow a worker to be paused on demand, the problem is that while in the loop the worker won't process messages and onmessage won't be called so I cannot send a "pause" message that sets a flag and then I check that flag in the loop.
What I thought of doing is to have my function yield after each iteration to allow the worker thread to process the message queue and then resume the function again if no pause signals is received, however, this feels a bit hacky.
Is there a way to force the WebWorker to process message queue without leaving the loop or yielding? or maybe a way to set a flag without going through onmessage()?
Thank you
onmessage
were executed simultaneously. If your platform supportsyield
I advise using it rather than terminating the loop. – Bema