JavaScript and Threads JavaScript and Threads javascript javascript

JavaScript and Threads


See http://caniuse.com/#search=worker for the most up-to-date support info.

The following was the state of support circa 2009.


The words you want to google for are JavaScript Worker Threads

Apart from from Gears there's nothing available right now, but there's plenty of talk about how to implement this so I guess watch this question as the answer will no doubt change in future.

Here's the relevant documentation for Gears: WorkerPool API

WHATWG has a Draft Recommendation for worker threads: Web Workers

And there's also Mozilla’s DOM Worker Threads


Update: June 2009, current state of browser support for JavaScript threads

Firefox 3.5 has web workers. Some demos of web workers, if you want to see them in action:

The Gears plugin can also be installed in Firefox.

Safari 4, and the WebKit nightlies have worker threads:

Chrome has Gears baked in, so it can do threads, although it requires a confirmation prompt from the user (and it uses a different API to web workers, although it will work in any browser with the Gears plugin installed):

  • Google Gears WorkerPool Demo (not a good example as it runs too fast to test in Chrome and Firefox, although IE runs it slow enough to see it blocking interaction)

IE8 and IE9 can only do threads with the Gears plugin installed


Different way to do multi-threading and Asynchronous in JavaScript

Before HTML5 JavaScript only allowed the execution of one thread per page.

There was some hacky way to simulate an asynchronous execution with Yield, setTimeout(), setInterval(), XMLHttpRequest or event handlers (see the end of this post for an example with yield and setTimeout()).

But with HTML5 we can now use Worker Threads to parallelize the execution of functions. Here is an example of use.


Real multi-threading

Multi-threading: JavaScript Worker Threads

HTML5 introduced Web Worker Threads (see: browsers compatibilities)
Note: IE9 and earlier versions do not support it.

These worker threads are JavaScript threads that run in background without affecting the performance of the page. For more information about Web Worker read the documentation or this tutorial.

Here is a simple example with 3 Web Worker threads that count to MAX_VALUE and show the current computed value in our page:

//As a worker normally take another JavaScript file to execute we convert the function in an URL: http://stackoverflow.com/a/16799132/2576706function getScriptPath(foo){ return window.URL.createObjectURL(new Blob([foo.toString().match(/^\s*function\s*\(\s*\)\s*\{(([\s\S](?!\}$))*[\s\S])/)[1]],{type:'text/javascript'})); }var MAX_VALUE = 10000;/* *	Here are the workers *///Worker 1var worker1 = new Worker(getScriptPath(function(){    self.addEventListener('message', function(e) {        var value = 0;        while(value <= e.data){            self.postMessage(value);            value++;        }    }, false);}));//We add a listener to the worker to get the response and show it in the pageworker1.addEventListener('message', function(e) {  document.getElementById("result1").innerHTML = e.data;}, false);//Worker 2var worker2 = new Worker(getScriptPath(function(){    self.addEventListener('message', function(e) {        var value = 0;        while(value <= e.data){            self.postMessage(value);            value++;        }    }, false);}));worker2.addEventListener('message', function(e) {  document.getElementById("result2").innerHTML = e.data;}, false);//Worker 3var worker3 = new Worker(getScriptPath(function(){    self.addEventListener('message', function(e) {        var value = 0;        while(value <= e.data){            self.postMessage(value);            value++;        }    }, false);}));worker3.addEventListener('message', function(e) {    document.getElementById("result3").innerHTML = e.data;}, false);// Start and send data to our worker.worker1.postMessage(MAX_VALUE); worker2.postMessage(MAX_VALUE); worker3.postMessage(MAX_VALUE);
<div id="result1"></div><div id="result2"></div><div id="result3"></div>