user2143645
user2143645

Reputation: 45

unable to send message to html webworker when the worker is busy

I am new to webworkers and below is my sample code

<body>
    <script type="text/javascript">
        var myWorker;
        $(document).ready(function () {

            myWorker = new Worker('worker.js');


            myWorker.onmessage = function (msg) {
                alert(msg.data);
            };


        });



        function SendMessage() {
            alert("send");
            myWorker.postMessage("test");
        }


        function SendMessage1() {
            alert("send1");
            myWorker.postMessage("1");

        }
    </script>


    <div id="target">df</div>
    <input type="button" id="test" name="sendMsg" onclick="SendMessage()" />
    <input type="button" id="test" name="sendMsg1" onclick="SendMessage1()" />
</body>

and below is the worker.js

var i = 0;

self.onmessage = function (msg) {
    console.log(msg.data);


    if (msg.data == "1") {
        postMessage(i);
    }
    else {
        test();
    }


}

function test() {

    while (1) {
        //console.log(i);
        i++;
    }
}

once the worker thread starts running the loop, no more messages are recieved by the worker thread. how can we send message to worker while the worker is busy with current operation?

Upvotes: 1

Views: 724

Answers (1)

Giulio Bambini
Giulio Bambini

Reputation: 4755

Workers work exactly the same as the main thread - if you have a loop running, no other tasks can be executed.

If you want to be able to process messages while running the loop, you need to break/pause the loop sometimes.

Simplest way to do that would be to wait on timeout from time to time:

// Promisification of setTimeout
function PromiseTimeout(delay) {
    return new Promise(function(resolve, reject) {
        setTimeout(resolve, delay);
    });
}


async function test() {
    while (1) {
        i++;
        // Every 10th iteration, this will execute
        if(i % 10 == 0) {
            await PromiseTimeout(0);
        }
    }
}

Note that this requires ES6 async/await features. It also obviously makes your loop slightly slower, since it has to pause on every 10th i.

Upvotes: 5

Related Questions