[英]HTML5 Web Worker does not respond to message
Consider the following code: 考虑以下代码:
worker.js worker.js
onmessage = function(evt){
postMessage({data:"foo",id:evt.data.id});
};
master.js (embedded in some HTML) master.js(嵌入一些HTML)
function startWorker(count){
var running = count;
for(var i = 0; i < count; i++){
console.log("Creating worker " + i);
var worker = new Worker("worker.js");
worker.onmessage = function(event){
console.log("Worker #" + event.data.id + " finished");
worker.terminate();
running--;
if(!running)
console.log("All worker finished");
}
worker.postMessage({id:i});
}
}
startWorker(3);
Whenever I execute this in Chrome or Firefox , most times I do only get the following output: 每当我在Chrome或Firefox中执行此操作时,大多数时候我只会得到以下输出:
Creating worker 0 Creating worker 1 Creating worker 2 Worker #0 finished Worker #1 finished
创建工作人员0创建工作人员1创建工作人员2工作人员#0已完成工作人员#1已完成
worker 2 is missing in the output, it never responds to the message. 输出中缺少工作程序2,它从不响应该消息。 However, if I retry this for several times, a few times all workers respond to my message.
但是,如果我重试几次,则所有工作人员都会几次响应我的消息。
Do you know what my problem might be? 你知道我的问题是什么吗? I created a Fiddle to test this behavior.
我创建了一个小提琴来测试这种行为。
The issue here is the variable worker
and how it's used inside the onmessage
function. 这里的问题是变量
worker
及其如何在onmessage
函数中使用。
The onmessage
function is async, and there's no special scope in for
loops, so the worker
variable is overwritten on each iteration and can't be used inside the onmessage
function, instead we could use this
, like this 该
onmessage
函数是异步,而且也没有在特殊范围for
循环,所以worker
变量被覆盖在每次迭代,并且不能在内部使用onmessage
函数,而不是我们可以用this
,像这样
for (var i = 0; i < count; i++) {
log("Creating worker " + i);
var worker = new Worker(url);
worker.onmessage = function (event) {
log("Worker #" + event.data.id + " finished");
this.terminate(); // "this" will be the correct worker
running--;
if (!running) console.log("All worker finished");
}
worker.postMessage({
id: i
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.