I'm trying to understand this example:
HTML (main code):
<html>
<title>Test threads fibonacci</title>
<body>
<div id="result"></div>
<script language="javascript">
var worker = new Worker("fibonacci.js");
worker.onmessage = function(event) {
document.getElementById("result").textContent = event.data;
dump("Got: " + event.data + "\n");
};
worker.onerror = function(error) {
dump("Worker error: " + error.message + "\n");
throw error;
};
worker.postMessage("5");
</script>
</body>
</html>
Javascript (worker code):
var results = [];
function resultReceiver(event) {
results.push(parseInt(event.data));
if (results.length == 2) {
postMessage(results[0] + results[1]);
}
}
function errorReceiver(event) {
throw event.data;
}
onmessage = function(event) {
var n = parseInt(event.data);
if (n == 0 || n == 1) {
postMessage(n);
return;
}
for (var i = 1; i <= 2; i++) {
var worker = new Worker("fibonacci.js");
worker.onmessage = resultReceiver;
worker.onerror = errorReceiver;
worker.postMessage(n - i);
}
};
I have the following questions:
When exactly the worker code starts to run ? Immediately after the execution of
var worker = new Worker("fibonacci.js");
?Is that true that
onmessage = function(event) { ... }
assignment in the worker code will be executed beforeworker.postMessage("5");
in the main code ?Can worker code access global variables that are defined in the main code (like
worker
)?Can main code access global variables that are defined in the worker code (like
results
)?It seems to me that
worker.onmessage = function(event) {...}
in the main code has the same meaning likeonmessage = function(event) {...}
in the worker code (which isonmessage
event handler of the worker). Where am I wrong ? What is the difference between them ?What this code should actually do ? When I run it here it just prints "5". Is that what it is supposed to do, or I'm missing something ?
Thanks a lot !