HTML and CSS Reference

In-Depth Information

is he worker instance (where this would otherwise be the

window
object).

In these examples so far, our worker hasn't done anything par-

ticularly special. How about a worker that searches for prime

numbers? This requires a super tight loop in JavaScript con-

stantly spinning around looking for values that match a prime.

All this and at the same time allowing your visitor to draw on a

canvas while your app searches for prime numbers? Perhaps a

strange use case, but we have workers to come to your rescue.

The main document will handle starting the worker and drawing

on the canvas. The only code that's offloaded to the worker is

the prime number searching.

var worker = new Worker('prime.js'),

prime = document.getElementById('prime');

worker.onmessage = function(event) {

prime.innerHTML = event.data;

};

The page continues to handle mousedown, move, and up

events to draw on a canvas on the page. Inside the
prime.js

script we have:

onmessage = function (event) {

// doesn't matter what the message is, just start the job

run();

};

function run() {

var n = 1;

search: while (true) {

n += 1;

for (var i = 2; i <= Math.sqrt(n); i += 1)

if (n % i == 0)

continue search;

// found a prime!

postMessage(n);

}

}

When the
prime.js
worker receives any message, it starts the

prime number search. When you run this prime number drawing

extravaganza of an application, everything runs smoothly, and

you're able to create your perfect work of art whilst also search-

ing for primes as seen in
Figure 10.2
.