HTML and CSS Reference
In-Depth Information
Using web workers
Now that you've examined the foundation of web workers, you can go back to the bounc-
ing ball example and move the intensive math operations over to a worker process so that it
doesn't interfere with the bouncing ball activity. To do this, create a new JavaScript file called
CalculateWorker.js with the following code in it:
onmessage = function (evt) {
var work = 10000000;
var i = 0;
var a = new Array(work);
var sum = 0;
for (i = 0; i < work; i++) {
a[i] = i * i;
sum += i * i;
This code starts with assigning the onmessage handler a function to run when spawned
within the context of a worker. At the end of the message, it calls postMessage to return
a result back to the caller. Save this file, and then change the click event handler for the
intensiveWork button in the bouncing ball code as follows:
document.getElementById("intensiveWork").onclick = function () {
var result = document.getElementById("workResult");
result.innerText = "";
var worker = new Worker("CalculateWorker.js");
worker.onmessage = function (evt) {
try {
result.innerText =;
} catch (e) {
worker.onerror = function (err) {
alert(err.message + err.filename + err.lineno);
In this code, the pattern described in the previous section is implemented. A new Worker
object is instantiated with CalculateWorker.js specified. Then the onmessage is assigned a
function to handle the result of the worker thread. The onerror is assigned a function to
handle any error conditions. Finally, the postMessage is called to invoke the worker.
Run this code and click the Do Work button. The ball now continues to move on the screen
and is responsive to the arrow keys. To make the worker process take longer, simply increase
the size of the number it needs to work with.
Search WWH ::

Custom Search