问题描述
假设我们有一个Web工作者引用一个名为worker.js的文件。我们使用worker在worker.js中执行一个执行一些冗长操作的函数。我们将相应的消息发布给工作者并在主线程中继续。但是,在工作人员完成初始工作之前,主线程会向其发送另一条消息。
Say we have a web worker referring to a file called "worker.js". We use the worker to execute a function in "worker.js" that does some lengthy operation. We call post the respective message to the worker and proceed in the main thread. However, before the worker has finished doing its initial work, the main thread posts another message to it.
我的问题:工人是否会继续执行我们的计时功能,只处理新发布的消息一旦完成,还是会中断当前操作直到新消息完成?
My question: Will the worker continue with our time-taking function and only process the newly posted message once finished or will it interrupt its current operation until the new one has been completed?
推荐答案
我'我在Google Chrome的调试器中尝试了以下代码:
I've tried out the following code in Google Chrome's debugger:
worker.js:
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});
}
输出:
(10000 times) test.js:11 hello world
test.js:14 xyz
每次重复迭代都会重新计算余弦变量,以提供问题中描述的计时算法。 显然,只有在最后一次操作完成后才会收到消息,因为我观察到在第10000次hello world输出后立即打印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.
这篇关于在Web工作程序仍在运行时向其发布消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!