Commit d628147b authored by Joel Martin's avatar Joel Martin

WebWorkers example with two way messages.

- Prime number background worker that can be started, stopped and
  reset that calculates prime numbers and sends them back to the main
  page/thread.
parent 85b7a7d4
<!DOCTYPE HTML>
<html>
<head>
<title>Worker example: One-core computation</title>
</head>
<body>
<p>The highest prime number discovered so far is: <output id="result"></output></p>
<input type='button' value="Start" onclick="worker.postMessage('start');">
<input type='button' value="Stop" onclick="worker.postMessage('stop');">
<input type='button' value="Reset" onclick="worker.postMessage('reset');">
<br>
Log:<br>
<textarea id='debug' style="font-size: 9;" cols=80 rows=25></textarea>
<script src="include/mootools.js"></script>
<script src="include/mootools-more.js"></script>
<script>
function debug(str) {
cell = $('debug');
cell.innerHTML += str + "\n";
cell.scrollTop = cell.scrollHeight;
}
debug('Starting');
var worker = new Worker('prime.js');
worker.onmessage = function (event) {
var cmd = event.data.substr(0,4);
var data = event.data.substr(4);
switch (cmd) {
case 'log:':
debug(data);
break;
case 'num:':
$('result').innerHTML = data;
break;
}
};
</script>
</body>
</html>
var n = 1;
var cur = 1;
var timer = null;
function search() {
if (timer) clearTimeout(timer);
var sqrtn = Math.sqrt(n);
for (iters = 0; iters < 10000; iters += 1) {
cur += 1;
if ((cur <= sqrtn) && (n % cur != 0)) continue;
if (cur > sqrtn) {
postMessage("num:" + n);
}
n += 1;
cur = 1;
}
timer = setTimeout(search, 10);
}
onmessage = function (e) {
switch (e.data) {
case 'start':
postMessage("log:start");
if (timer) clearTimeout(timer);
timer = setTimeout(search, 100);
break;
case 'stop':
postMessage("log:stop");
if (timer) clearTimeout(timer);
started = false;
break;
case 'reset':
postMessage("log:reset");
n = 1;
postMessage('num:');
break;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment