HTML and CSS Reference

In-Depth Information

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
,
mousemove
, and
mouseup

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
.