Check out HTML5 Rocks: Webmaster Fundamentals for a General Tutorial.
- Workers will begin work immediately after calling the
postMessage method of the worker. - a function related to working
onmessage in the main code will work when the worker calls postMessage . - global variables are not shared between main and worker threads. The only way to transfer data is through messaging through
postMessage . - as you suspected,
onmessage for the working and main code has the same meaning. This is an event handler when a thread receives a message event. You can even use addEventListener instead, catching the 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);
Work code:
addEventListener('message', resultReceiver, false);
The example of the fibonacci you took is an example of a recursive worker. If you do not use workers, it will 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 make a stem for you). You write yourself!)
source share