HTML and CSS Reference
In-Depth Information
To test if the browser supports Web Workers, use the following feature-detect for the
Worker API:
var webworkers_support = !!window.Worker;
Now let's build a simple Web Workers demo. We'll initialize a large two-dimensional
array with random numbers, a task that may take long enough to cause a noticeable
UI delay. (You might use such a 2D array of random numbers to represent random
pixels in a canvas element; see Chapter 9 .) Two nested for loops do the trick:
var data = [];
for (var i=0; i<1500; i++) {
data[i] = [];
for (var j=0; j<1500; j++) {
data[i][j] = Math.random();
}
}
There's nothing particularly exciting going on here. Such an array, with 2.25 million
(1500 × 1500) operations to initialize it, may very well lock up the UI for anywhere
from 2 to 30 seconds, depending on browser and device capability.
A more graceful way to handle this, without locking the UI, is to put such an operation
into a separate thread—a Web Worker—and simply wait to be notified of it finishing
before continuing.
To do this, put the above code into a separate file (called, for instance, init_array.js )
and wrap the code in an onmessage event handler:
self.onmessage = function(evt) {
var data = [];
for (var i=0; i<1500; i++) {
data[i] = [];
for (var j=0; j<1500; j++) {
data[i][j] = Math.random();
}
}
self.postMessage (data);
data = null; // unassign our copy of the data now, to free up memory
};
This is the code for the Web Worker. The code first tells the worker to listen for the
message event, which lets the worker know when to start. Once started, the worker
performs the long-running computation. Finally, the worker sends back a message (the
data array in our example), using postMessage(...) , to the main page. Workers can
also be started by other workers, and the communication works exactly the same.
 
Search WWH ::




Custom Search