# Calculate Prime Number using web workers and Web storage in HTML5

Take a number input (less than 100) from the user and save it to the web storage. Create a web worker to increment the number till it becomes prime. Provide two buttons of 'Start' and 'End' to start or end the process. The increment stops upon pressing 'end', or the number becomes prime.

<!DOCTYPE HTML>
<html>
<title>Prime Number - Web Workers</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="prime.js"></script>
<style>
button {
height: 32px;
background: #0071e3 !important;
border: 1px solid transparent;
color: #fff;
}
</style>
<body style="background-color: #fafafa;margin: 0 auto;text-align: center;font-family: Arial, Helvetica, sans-serif;">
<span style="position: relative;top:20px">
Prime Number
</span>
</div>
<br/>
<br/>
<span style="margin-right: 10px;">Enter number to find prime numbers</span>
<input type="text" name="checkValue" id="checkValue" max="100" style="height:28px;border:1px solid #8b8b8b;font-size: 15px;border-radius: 4px;"/>
<span>
<button onclick="enablePrime()" title="Start Prime Check">Start</button>
<button onclick="terminatePrime()" title="Terminate Prime check">Stop</button>
</span>
</div>
<br/>
<div>
<output id="primeResult"></output>
<div id="outputData"></div>
</div>
</div>
</body>
</html>

Prime.js

var primeWorker;

function enablePrime() {
primeWorker = new Worker("webworkers.js");
var maxValue = $('#checkValue').val(); primeWorker.addEventListener("message", handlePrime, false); primeWorker.postMessage({'cmd': 'start', 'upto': maxValue}); } function terminatePrime() { if (primeWorker != undefined) { primeWorker.terminate(); } } function handlePrime(event) {$('#outputData').append(JSON.stringify(event.data) );
}

Webworkers.js

function getPrimes(max) {
var primeNum = [], i, j, primes = [];
for (i = 2; i <= max; ++i) {
primes.push(i);
for (j = i << 1; j <= max; j += i) {
}
}
}
return primes;
}
var data = e.data;
switch (data.cmd) {
case 'stop':
self.close();
break;
case 'start':
var numbers = getPrimes(data.upto);
postMessage("Prime Numbers are: "+ numbers + "<br/>");
break;
default:
postMessage('unknown command: ' + data.msg);
}
}, false);

Your code is pretty much fine with what you are wanting to do. You might like to make the following changes:

HTML:

• Change the max attribute to 99 to ensure the input is less than 100.
• Move inline event handlers to addEventListener for better practice.

Prime.js:

• Store the number in a local storage.
• Update the handlePrime function to display results more cleanly.

Webworkers.js:

• Create a function to check if a number is prime.
• Increment the number until it becomes prime, or the worker is terminated.