Thursday, July 21, 2011

Recursively spawning Web Workers

I like to think of HTML5 Web Workers simply as 'threading for the Web'.

Wikipedia describes it a bit more in detail.
Web Workers define an API for running scripts, basically JavaScript, in the background independently of any user interface scripts. This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.
You can start a Web Worker like this.

if (typeof(Worker) === "undefined") {
    alert("Web Workers not supported in your browser.");
} else {
    var worker = new Worker("worker.js");
}

The Web Worker API allows workers to create subworkers. The fun quirk here is that you can start a worker that recursively spawns another worker with the same JavaScript file.

So in worker.js, you can do this.

var worker = new Worker("worker.js");

And as you can guess, this has some interesting effects.


Try it yourself here.

1 comment:

  1. Even better:

    while(1)
    new Worker("worker.js");

    ReplyDelete