In a simple HTML5 web worker project, I have defined a web worker which exchanges messages using HTML5 messaging API. There is a source of confusion for me here due to the fact that we have defined two .onmessage handlers (callback functions), one in the main script and the other one in the worker.js:
index.html:
<!DOCTYPE html>
<html>
<body>
<script>
var worker = new Worker("worker.js");
worker.onmessage = function(event) {
alert("Reply from index.html:"+event.data);
}
worker.postMessage("message 3,");
</script>
</body>
</html>
worker.js:
this.onmessage = function(event) {
postMessage("message 0,"+event.data);
}
postMessage("message 1,");
one thing that i don’t get is the order of messages being displayed!
it first displays this:

and then displays this

But why? I am confused how and when these handlers were called? first the worker.postMessage(“message 3,”); triggers the worker.postMessage(“message 3,”); in worker.js and postMessage(“message 0,”+event.data); in returns triggers the worker.onmessage = function(event) in the main script! then at the very end the postMessage(“message 1,”); from the worker.js triggers the onmessage of the main script(index.html). Can we say we are any postMessage call on a worker triggers the onmessage function of other web workers?
You might be confusing the Web Worker implementation with js methods that you may pass the objects as a function. WEB WORKERS in HTML5 are are bringing the THREADING TO JAVASCRIPT.
Reason seems to be in the append event of ‘.onmessage’ and your
worker.jsstarts with posted expression ‘postMessage(“message 0,”+event.data);’ . Themessage 0comes first because of that reason.A good introductory tutorial like the following one should address your concerns – THE BASICS OF WEB WORKERS.