问题
I"m learning about HTML5 workers from here and the author uses self.onmessage
and self.postmessage
to communicate between the main thread and the worker "because the worker cannot access the DOM." But in the below it seems like self
is referring to both the main thread and the worker.
function CalculatePi(loop)
{
var c = parseInt(loop);
var f = parseFloat(loop);
var n=1;
//these errors will need more work…
if (isNaN(c) || f != c ) {
throw("errInvalidNumber");
} else if (c<=0) {
throw("errNegativeNumber");
}
for (var i=0,Pi=0;i<=c;i++) {
Pi=Pi+(4/n)-(4/(n+2));
n=n+4;
}
self.postMessage({'PiValue': Pi});
}
//wait for the start 'CalculatePi' message
//e is the event and e.data contains the JSON object
self.onmessage = function(e) {
CalculatePi(e.data.value);
}
The above code is from a separate js file containing the worker, and I understand that the self
in self.onmessage
is referring to the worker receiving a message from the main thread to start calculating, but why would it use self.postMessage
to post a message back to itself? Is the default receipt(s) of #postMessage and #onmessage include both the main thread and worker?
Later on, the author posts the calucation of pi through this function:
worker.onmessage = function(e) {
document.getElementById("PiValue").innerHTML = e.data.PiValue;
};
How does this work when the worker isn't suppose to have access to the DOM? It clearly is using document.getElementById here.
回答1:
in your file worker.js think of the self.postMessage
as the order/instruction that the worker (self) should post a message. Since it is only able to communicate with the mainJS which created it, this message goes there. :)
Also in your mainJS worker.onmessage
should be understood as the event "a message comes from the worker".
So basically you have both options in both your scripts:
in mainJS: worker.postMessage("message");
to send a message to the worker - and worker.onmessage = function(event){...}
to listen to messages from the worker
in worker script: (self or) this.onmessage = function(event){...}
to listen to messages from the mainJS - and self.postMessage("message");
to send something back to mainJS
来源:https://stackoverflow.com/questions/38532535/how-does-onmessage-and-postmessage-work-to-communicate-between-main-thread-and