WebWorker loop interruption

I have a dedicated web worker who, after receiving the start signal, goes into a long cycle and, based on some start parameters, the cycle will “yield” at certain 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 allow the employee to pause on demand, the problem is that during the cycle the worker will not process messages, and onmessage will not be called, so I can not send the message "pause" which sets the flag, and then I I check this flag in a loop.

What I was thinking of doing was getting my function after each iteration so that the workflow would process the message queue and then resume the function again if there were no pause signals, however this is a bit hacked.

WebWorker , ? , , onmessage()?

+4

Source: https://habr.com/ru/post/1625124/


All Articles