Javascript eventListener inside while loop

I am trying to figure out whether it is possible in Javascript to implement an eventListener into a while loop which can pass a value to a variable inside the loop. I need this to cancel an infinite loop which continiously should send a data frame to a TCP-socket (watchdog). When the socket is closed the loop should end. I use a webworker for this purpose, but it does not work.
Here is the code:

// WebWorker with infinite loop

var check = "true";
let i=0;
let j=0;
var returnedEvent;

while(check){

self.postMessage(i);


onmessage = (event) => { 

    returnedEvent = event.data;
    console.log("worker: " + event.data);
    let check = returnedEvent;  
    }
    
    sleep(100);
    
}
console.log("loop completed");

function sleep(delay)
    {
    var start = new Date().getTime();
        while (new Date().getTime() < start + delay);
    }

in