Game Development Reference
In-Depth Information
// get-primes.worker.js
// Register the onMessage callback
self.addEventListener("message", getPrimes);
// This function implements the Sieve of
Eratosthenes to generate the primes.
// Don't worry about the algorithm so much -
focus on the Worker API
function getPrimes(event) {
var max = event.data.max;
var primes = [];
var d = [];
for (var q = 2; q < max; q++) {
if (d[q]) {
for (var i = 0; i < d[q].length; i++) {
var p = d[q][i];
if (d[p + q])
d[p + q].push(p);
else
d[p + q] = [p];
}
delete d[q];
} else {
primes.push(q);
if (q * q < max)
d[q * q] = [q];
}
}
// Return the list of primes to the parent
thread
self.postMessage({primes: primes});
}
Search WWH ::




Custom Search