1

所以我有这个主要的js文件:

var worker = new Worker("../Scripts/worker.js");
worker.onmessage = function (event) {
    alert("Worker said : " + event.data);
};
worker.postMessage("Naruto");
worker.postMessage("Sakura");

worker.js 在这里:

self.onmessage = function (event) {
      self.postMessage("Hi " + event.data);
};

self.postMessage("WHERE'S SASUKE? [1]");
self.postMessage("WHERE'S SASUKE? [2]");

我仍然对它们的实际工作方式有些困惑。但结果是这样的(按出现顺序):

Worker said: WHERE'S SASUKE? [1]
Worker said: WHERE'S SASUKE? [2]
Worker said: Hi Naruto
Worker said: Hi Sakura

他们说要启动一个工人,请使用 postMessage()。

第一个问题:那么如果我的主js文件postMessage(“Naruto”),为什么worker首先显示两个“WHERE'S SASUKE?” 然后显示鸣人和小樱?它不是应该首先触发它的 onMessage 事件,因为它从主线程接收到数据吗?

第二个问题:当我发布消息(“火影忍者”)时,它显示了两个“佐助在哪里?”。但是为什么当我做 postMessage("Sakura") 时,它没有显示两个“WHERE'S SASUKE?”?我的意思是,我在主线程中调用了 postMessage() 两次,为什么只显示两个“WHERE'S SASUKE”?难道它不应该“执行”worker.js 两次也因此看到四个“WHERE'S SASUKE?”?(请赐教)

4

1 回答 1

1

一些注释可以帮助您了解正在发生的事情

main.js

var worker = new Worker("../Scripts/worker.js");

// register handler, 
// code is executed only when a message is received from worker
worker.onmessage = function (event) {
    alert("Worker said : " + event.data);
};

worker.js

// register onmessage handler , 
// code will not be executed at this point but only when you post a message
self.onmessage = function (event) {
      self.postMessage("Hi " + event.data);
};

// these are executed immediately
// they will be executed only once during the 'new Worker' part
self.postMessage("WHERE'S SASUKE? [1]");
self.postMessage("WHERE'S SASUKE? [2]");
于 2013-01-19T08:40:16.880 回答