Posting a message to a web worker while it is still running

倖福魔咒の 提交于 2019-12-01 17:55:33

I've tried out the following code in Google Chrome's debugger:

worker.js:

var cosine;
self.onmessage = function(e) {
    if (e.data.message == 0) {
        for (var i = 0; i < 10000000; i++) {
            cosine = Math.cos(Math.random());
            if (i % 1000 == 0) console.log("hello world");
        }
    } else if (e.data.message == 1) {
        console.log("xyz");
    }
};

main.js:

var worker;

function main() {
    worker = new Worker("js/worker.js");
    worker.postMessage({message: 0});
    setTimeout(xyz, 10);
}

function xyz() {
    worker.postMessage({message: 1});
}

output:

(10000 times) test.js:11 hello world
test.js:14 xyz

The cosine variable is recalculated with every new iteration to provide the "time-taking" algorithm described in the question. Apparently, the message is only received as soon as the last operation has finished, as I observed the "xyz" output being printed immediately after the 10000th "hello world" output.

A Web Worker is backed by a single thread. This means that while the "onmessage" handler is being executed, it will not be able to receive another "onmessage" event until the previous one has finished.

This is quite inconvenient if we want to implement some background computation process that we want to be able to pause and resume, because there is no way to send a "pause" message to a running worker. We are able to stop a web worker via worker.terminate(), but that completely kills the worker.

The only way I can think of is by slicing worker execution into chunks, then post a message from the worker at the end of each chunk, which then triggers a message to the worker to process the next chunk, and so on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!