raberana
raberana

Reputation: 11816

HTML5 WebWorker Logic flow

So I have this main js file:

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

and worker.js is here:

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

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

I'm still a little bit confused on how they actually work. But what comes out is this (in order of appearance):

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

They said that to start a worker, use the postMesage().

First question: So if my main js file postMessage("Naruto"), why did the worker displayed first the two "WHERE'S SASUKE?" and then displayed Naruto and Sakura? Isnt it supposed to trigger its onMessage event first because it received a data from the main thread?

Second question: When I postMessage("Naruto"), it showed the two "WHERE'S SASUKE?". But why is that when I do postMessage("Sakura"), it didnt show the two "WHERE'S SASUKE?"? I mean, I called postMessage() in the main thread twice, why is that there's only two "WHERE'S SASUKE" displayed? Isnt it supposed to 'execute' the worker.js twice also thus seeing four "WHERE'S SASUKE?"? (Enlighten me please)

Upvotes: 1

Views: 300

Answers (1)

lostsource
lostsource

Reputation: 21850

Some annotations which may help you understand what's going on

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]");

Upvotes: 1

Related Questions