HTML5 Zone is brought to you in partnership with:

Kristof Degrave is a Microsoft Certified Technology Specialist ASP.NET and has a broad interest in web development. He works as a software engineer for RealDolmen, one of Belgium's biggest ICT companies, where he takes on the role of squadleader for the web squad, a group of web-enthousiasts within the Microsoft Division. He mainly focuses on HTML5 and related technologies, such as CSS3, jQuery, ... He is currently working on a library on top of the IndexedDB API called Linq2indexedDB. The goal of this library is an easy-to-use query interface with extended filter, sort and select capabilities. The library can be found on http://linq2indexeddb.codeplex.com Kristof is a DZone MVB and is not an employee of DZone and has posted 15 posts at DZone. You can read more from them at their website. View Full User Profile

Web Worker: Running JS Tasks in the Background

05.07.2012
| 4835 views |
  • submit to reddit

Since JavaScript is more and more used for building applications, rather than providing extra features, you need to take care you don’t freeze the UI. This is one of the reasons why the W3C introduced the web worker API. This API provides a way to run JavaScript in a thread different from the UI thread. This way long running code such as sorting large array’s, won’t freeze the the UI or make your application unresponsive. Generally, workers are expected to be long-lived, have a high startup performance cost and a high per-instance memory cost.

workers

When we want to run code in a thread different from the UI thread, then we need to put this code in separate file. This file, will then be called by the worker to run in another thread. The only thing you need to do in the in the code that will run in another thread is calling postMessage method whenever you want to send data to the UI-thread.

Continuous worker

This code will start running when ever a worker with that file is instantiated and will continue running.

Example of a file (prime.js) to run in the background:

var n = 1;
prime: while(true){
    n += 1;
    for (var i = 2; i <= Math.sqrt(n); i += 1){
        if (n % i == 0){
            continue prime;
        }
    }
    // Found prime
    postMessage(n)
}

This code will send a message to the UI thread every time a prime is found.

// Starts a new worker
var worker = new Worker('prime.js');
worker.onmessage = function (event){
    // event.data contains a prime
    document.getElementById("result").textContent = event.data
}

The code above is used to create a new worker. The worker will execute the code in the prime.js file in a thread separate from the UI. In our case, the code will start calculating which numbers are primes.

The onmessage event on the worker gets triggered every time the postMessage method is called inside the worker thread. This way we can display the prime on the screen.

Dedicated worker

This worker will only start executing when you call the postMessage method on the worker.

Example of a file (sort.js) to run in the background:

onmessage = function (event) {
    var data = event.data.data;
    var propertyName = event.data.propertyName;
    var sortedData = data.sort(JSONComparer(propertyName).sort);
    postMessage(sortedData);
    return;
};
 
function JSONComparer(propertyName) {
    return {
        sort: function (valueX, valueY) {
                return ((valueX[propertyName] == valueY[propertyName]) 
                        ? 0 : ((valueX[propertyName] > valueY[propertyName]) ? 1 : -1));
        }
    }
}

The onmessage method will handle a postMessage send to the worker. This will start the work you want to execute. In this case the code will sort an array of JSON objects on a given property. When the array and the propertyName is provided as data in the postMessage method, The data will get sorted on the property with the given propertyName. When the sort is completed, the sorted array will be send to the UI.

var worker = new Worker("sort.js");
var data = [{ name: "test2" }, [{ name: "test4" }, [{ name: "test1" }, [{ name: "test3" }]
worker.onmessage = function (event) { /* event.data contains the sorted Array */) };
worker.postMessage({ data: data, propertyName: "name"});

With the postMessage method we can provide the data that is needed to sort an array. When the sorting is completed and the postMessage method in the background thread is called, the onmessage function will be triggered in the UI thread so we can process the sorted array.

More information about workers can be found here.
Published at DZone with permission of Kristof Degrave, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)