Is it possible to write a simple dedicated web worker so it process something continuously and sends its state only when the client asks.
What I've done so far, the Client file :
<script>
// spawn a worker
var worker = new Worker('basic-worker.js');
// decide what to do when the worker sends us a message
worker.onmessage = function(e){
document.getElementById('result').textContent = e.data;
};
</script>
<html>
<head></head>
<body>
<p>The Highest prime number discovered so far : <outpout id="result"></output></p>
</body>
</html>
The worker file :
var n = 0;
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);
}
As you can see the worker send continuously the primes it founds. I would like to be able to launch the prime calculation and asks the worker to send the latest prime he founds when I click a button on the client for example. That would be something like (I know it cannot work as but to give a general idea of what i want) :
Worker file :
var n = 0;
var lPrime = 0;
// post last prime number when receiving a message
onmessage = function(e) {
postMessage(lPrime);
}
// continously search for prime numbers
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);
lPrime = n;
}
Client file :
<script>
// spawn a worker
var worker = new Worker('basic-worker.js');
// what to do when the worker sends us a message
worker.onmessage = function(e){
document.getElementById('result').textContent = e.data;
};
// post to the worker so the worker sends us the latest prime found
function askPrime(){
worker.postMessage();
};
</script>
<html>
<head></head>
<body>
<p>The Highest prime number discovered so far : <outpout id="result"></output></p>
<input type="button" onclick="askPrime();">
</body>
</html>