0

I'm experimenting with web worker but it seems that my simple worker is stuck in a loop. this is the initializer:

(() => {
    
    let worker = new Worker("/js/worker.js", {type: 'module'});
    worker.onmessage = e => {
        console.log(e);
    }
    
    window.onload = e => {
        
        document.getElementById("btnGo").addEventListener("click", async () => {            
            worker.postMessage({payload: 'dscds'});
        });
        
    }
    
})()

and then worker.js that will spawn subworkers

onmessage = async(e) => {

    let arr = [];
    let worker = new Worker("/js/subworker.js", {type: 'module'});
    worker.onmessage = e => {
        arr.push(e.data);
    }
    while(arr.length < 33){
        worker.postMessage({});
        console.info('in while ' + arr.length);
    }
    
    postMessage('blah');    

}

and finally, subworker.js, sweet and simple

onmessage = async(e) => {
    postMessage({});
}

so, the idea here is that subworker will keep churning empty response until there are 33 empty elements in the arr, but for some reason, it's looping forever inside while(arr.length < 33) inside worker.js. Am I misunderstanding anything?

thanks

Das Raf
  • 55
  • 6
  • Your worker's code still runs on a single thread, even if it did spawn a new sub-Worker. So your `while` loop is still blocking that one thread, and the event-loop that's waiting for the JS execution to be done will also be blocked and won't be able to handle any new message event. – Kaiido Feb 06 '23 at 08:10

0 Answers0