<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body class="blocking">
<h1>Searching prime numbers by using a web worker</h1>
<label for="limit">Limit
<input id="limit" type="number" value="10000">
</label>
<button class="search">start search</button>
<div class="prime-numbers"></div>
<script src="script.js"></script>
</body>
</html>
(function(w, d) {
d.querySelector('.search').addEventListener('click', function() {
// Create a new worker with the worker script
var worker = new Worker('worker.js');
// Adding an event listener to receive postMessage events from the worker
worker.addEventListener('message', function(e) {
var primeElement = d.createElement('span');
primeElement.classList.add('prime');
primeElement.textContent = e.data.prime;
d.querySelector('.prime-numbers').appendChild(primeElement);
});
// To start the worker we need to post an initial message where we also pass
// in parameters to the worker.
worker.postMessage({
limit: d.querySelector('#limit').value
});
});
}(window, document));
@import url("http://fonts.googleapis.com/css?family=Open+Sans:400,300,600");
*, *:before, *:after {
box-sizing: border-box;
-webkit-appearance: none;
-moz-appearance: none;
-ms-appearance: none;
appearance: none;
}
*:before, *:after {
content: '';
clear: both;
}
.blocking {
font-family: "Open Sans", sans-serif;
color: rgba(0, 0, 0, 0.8);
font-size: 1rem;
text-align: center;
h1 {
text-transform: uppercase;
text-align: center;
}
label {
display: block;
text-align: center;
input {
width: 10ch;
padding: 0.3em;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
background: transparent;
font-family: "Open Sans", sans-serif;
font-size: 1em;
color: rgba(0, 0, 0, 0.8);
}
}
button {
display: inline-block;
margin: 2em 0 3em 0;
padding: 1em 2em;
border: 3px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
background: transparent;
font-family: "Open Sans", sans-serif;
text-transform: uppercase;
font-weight: 200;
font-size: 1em;
color: rgba(0, 0, 0, 0.5);
transition: all 0.3s ease-out;
&:hover {
outline: none;
border-color: #000064;
color: rgba(0, 0, 0, 0.8);
}
&:focus {
outline: none;
}
}
.prime {
display: inline-block;
margin: 0.5em;
width: 3em;
height: 3em;
background-color: #000064;
line-height: 3em;
color: white;
border-radius: 3em;
}
}
(function(s) {
function findPrimeNumbers(limit) {
var isPrime,
i,
j;
for(i = 1; i < limit; i++) {
isPrime = true;
for(j = 2; j < i; j++) {
if(i % j === 0) {
isPrime = false;
}
}
if(isPrime) {
// Instead of accessing the DOM (which is not possible in workers anyway)
// we will fire a postMessage event and the host is listening for it.
s.postMessage({
prime: i
});
}
}
}
// Here is the entry point for the worker. It will start the thread by
// receiving a postMessage from a Web Worker host.
s.addEventListener('message', function(e) {
findPrimeNumbers(e.data.limit);
});
}(self));