Friday, February 17, 2012

Web worker: running js tasks in the background

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 form 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.


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:

   1: var n = 1;
   2: prime: while(true){
   3:     n += 1;
   4:     for (var i = 2; i <= Math.sqrt(n); i += 1){
   5:         if (n % i == 0){
   6:             continue prime;
   7:         }
   8:     }
   9:     // Found prime
  10:     postMessage(n)
  11: }

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

   1: // Starts a new worker
   2: var worker = new Worker('prime.js');
   3: worker.onmessage = function (event){
   4:     // contains a prime
   5:     document.getElementById("result").textContent =
   6: }

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:

   1: onmessage = function (event) {
   2:     var data =;
   3:     var propertyName =;
   4:     var sortedData = data.sort(JSONComparer(propertyName).sort);
   5:     postMessage(sortedData);
   6:     return;
   7: };
   9: function JSONComparer(propertyName) {
  10:     return {
  11:         sort: function (valueX, valueY) {
  12:                 return ((valueX[propertyName] == valueY[propertyName]) 
  13:                         ? 0 : ((valueX[propertyName] > valueY[propertyName]) ? 1 : -1));
  14:         }
  15:     }
  16: }

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.

   1: var worker = new Worker("sort.js");
   2: var data = [{ name: "test2" }, [{ name: "test4" }, [{ name: "test1" }, [{ name: "test3" }]
   3: worker.onmessage = function (event) { /* contains the sorted Array */) };
   4: 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.


  1. It is really nice for me to see you and your great hardwork again.Every piece of your work look excellent.Looking forward to learing more from you!
    iPad Application Development

  2. I have been liking every piece of what you publish, it feels nice reading this from you again as i lookm forward to reading more posts from you, keep up the great job.