I\'m trying to understand this example:
HTML (main code):
Test threads fibonacci
Check out HTML5 Rocks: The Basics of Web Workers for general tutorial.
postMessage
method of the worker.onmessage
in the main code will work when the worker calls postMessage
.postMessage
.onmessage
on both worker and main code has the same meaning. It is an event handler for when the thread receives a message event. You can even use addEventListener
instead, catching message
event:Main Code:
function showResult(event) {
document.getElementById("result").textContent = event.data;
dump("Got: " + event.data + "\n");
}
var worker = new Worker("fibonacci.js");
worker.addEventListener('message', showResult, false);
Worker code:
addEventListener('message', resultReceiver, false);
The fibonacci example you took is a recursive worker example. If not using workers, it would be something like this:
function fibonacci(n) {
if (n == 0 || n == 1) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
var result = fibonacci(5);
dump("Got: " + result + "\n");
(oh no, I'm not going to do a stackless for you. You write it yourself!)
I also want to add that you can debug web workers only in Chromium based browsers. You have to select Sources in developer panel and in right column expand bottom line Workers and then choose check box pause on start.