Web Development > Web Workers

  1. Overview
  2. Cross Browser Implementation
  3. Examples

Examples

Let's first take the simplest example from the Web Worker documentation, slightly modified, a rudimentary prime number search. The script on the page is given by

var nMax = 0;
var worker = new Worker('prime_search.js');
worker.onmessage = function (event)
{
	var n = event.data;
	if(n > nMax)
	{
		nMax = n;
		document.getElementById('result').innerHTML = n;
	}
};

The code contained in prime_search.js run by the worker is

var n = 1;
search: while(n < 50000)
{
	n += 1;
	for(var i = 2; i <= Math.sqrt(n); i += 1)
	{
		if(n % i == 0)
		{
			continue search;
		}
	}
	// found a prime!
	postMessage(n);
}

This finds all primes up to 50000, outputing the highest to the interface. Try it out:

Native Web Worker support:
Generate Primes
Highest prime found: --

So this should work whether you have Native Web Worker support or not. Note that in the cases where Workers are native the calculation does no interfere with the interface, however when native support is not present the calculation is being performed on the same thread as the interface and things lock up until the calculation is complete.

Well that was pretty boring, huh? So let's quit this town and move on to a much more exciting use of web workers in my JavaScript Paint application.