Check out HTML5 Rocks: The Basics of Web Workers for general tutorial.
- Workers will start as soon as you call the
postMessage
method of the worker.
- the function bound to worker's
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 pass data is through messaging via
postMessage
.
- as you suspected, the
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 + "
");
}
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 + "
");
(oh no, I'm not going to do a stackless for you. You write it yourself!)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…