Skip to navigation

Workers unite!

Web Workers are part of HTML 5 and already featured in Firefox 3.5 and Safari 4. A worker is a script that can be dynamically loaded by  the main page (or other workers). it runs in isolation in a background thread and only communicate with its caller through string messages.

They can be used to to increase user interface responsiveness by taking care of computations that would otherwise run in the main UI thread.

The UI freeze

Let’s see what happens when we run a long computation in the main thread. Try clicking on all checkboxes during the computation and notice how all clicks are queued and processed once the computation finishes (read about asynchronous events and timers).

 Workers to the rescue!

Let’s run the same computation but this time inside a worker.  Again, try to click the checkboxes (you need Firefox 3.5 or Safari 4), see how the UI responds immediately?

The setTimeout pattern 

Traditionally, to prevent blocking the browser, one would break long computations into smaller ones and use  setTimeout to schedule execution as Julien Lecompte explains.

He applies this method to sort an array. Every pass through the array is scheduled to run with setTimeout:

function sort (progressFn) {
  var i = 0;
  (function () {
    ... // sorting code here
    i++;
    progressFn(i, length);
    // schedule the current function for execution
    if (i < length) {
      setTimeout(arguments.callee, 0);
    }
  })();
}

Try it : sort without worker

Sort with a Worker

Now let’s put his sorting code into a worker, it should run a lot faster (no callback overhead) and has the advantage of not mixing scheduling with sorting code:

function sort (progressFn) {
  i = 0;
  var sort_loop = function () {
    ... // sorting code here
    i++;
    progressFn(i, length);
    if (i < length) {
      sort_loop();
    }
  };
  sort_loop();
}

Try it: sort with worker (you need Firefox 3.5).

There you go, UI responsiveness without the pain of chopping your code  into digestive chunks !

While Workers are not yet implemented in all browsers (the spec is still evolving),  be prepared! By allowing us to separate UI  from application logic and giving us multiple threads of execution, Workers will help us build bigger and better web applications… and maybe overthrow that funky boss !

Related links

How Javascript Timers Work

Running CPU Intensive JavaScript Computations in a Web Browser

Computing with Javascript Web Workers

Mozilla Dev Center: Using Web Workers

Love what we’ve said? Think we’re talking nonsense? Don’t worry about being polite, just let us have it. We’re not afraid of telling you that you’re talking crap, so don’t be afraid of telling us the same.