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)
Some annotations which may help you understand what’s going on
main.js
worker.js