HTML5 Web Worker Logic流程

时间:2013-01-19 08:24:43

标签: javascript html5 web-worker

所以我有这个主要的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

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

第一个问题: 所以,如果我的主js文件postMessage(“火影忍者”),为什么工人首先显示两个“在哪里SASUKE?”然后显示火影忍者和樱花?它是否应该首先触发其onMessage事件,因为它从主线程接收到数据?

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

1 个答案:

答案 0 :(得分: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]");