HTML and CSS Reference
In-Depth Information
Unlike in normal JavaScript operations, where passing an object around
is done by reference, the data passed in worker messages is copied , which
means that double the memory is consumed during the transmission.
For most types of data, this is not an issue to be concerned with.
But in our example with the large array, the considerable memory usage
is something to watch out for as it may cause issues on memory-limited
mobile devices. To conserve memory, only keep variables with large
amounts of data in them around for the shortest amount of time
necessary.
In the main page of our UI, we create the worker, pointing it at the appropriate file.
Then we set up a listener for the message event, to receive the message (the initialized
array) from the worker when it finishes its job. Finally, we start the worker by sending
it an empty message using postMessage() :
var worker = new Worker ("init_array.js");
worker. onmessage = function(evt) {
alert("Data array initialization finished!");
var data = evt.data ;
};
worker. postMessage (); // tell our worker to start its task
Discussion
Web Workers are very useful for offloading complex or long-running tasks to another
thread, something that JavaScript itself cannot do.
If Web Workers are not supported in a particular browser, you'll need to just run your
code in the main JavaScript thread, and deal with the delays it may cause. In some
circumstances, you can break up your long-running code into smaller chunks and run
one chunk at a time, pausing briefly in between to let the UI update before resuming.
For example:
function doNextChunk() {
var done_yet = false;
for (var i=0; i<500; i++) { // do 500 iterations at a time
// do something
// when done, set done_yet = true
}
if (!done_yet) setTimeout(doNextChunk,0);
else alert("All done finally!");
}
doNextChunk();
Using a setTimeout(...,0) pattern, we do 500 iterations of a long-running loop, pause
for a brief moment (just long enough for the UI to update), then resume and do another
500 iterations, and so on. This technique has better performance than letting a long-
 
Search WWH ::




Custom Search