Simple Web Workers

Warning: Your browser doesn't support Web Workers.

Demo

The in page JavaScript

var worker = null;
$('#btnStart').click(function () {
    if (!worker) {
        $('#primes').empty();
        if (!!window.Worker) {
            worker = new Worker('/Scripts/SimplePrimes.js');
            worker.onmessage = function (e) {
                $('<li>').text(e.data).prependTo('#primes');
            };
        } else {
            $('<li>').text('Web Worker is not supported :-(').prependTo('#primes');
        }
    }
});

$('#btnStop').click(function () {
    if (worker) {
        worker.terminate();
        worker = null;
        $('<li>').text('Terminated').prependTo('#primes');
    }
});

The SimplePrimes.js loaded bij the Worker object

for (var i = 2; i < 100000; i++) {
    var isPrime = true;
    for (var d = 2; d < i; d++) {
        if (i % d === 0) {
            isPrime = false;
            break;
        }
    }

    if (isPrime) {
        postMessage(i);
    }
}