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.
This commit is contained in:
parent
85b7a7d411
commit
d628147bca
40
prime.html
Normal file
40
prime.html
Normal file
@ -0,0 +1,40 @@
|
||||
<!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>
|
39
prime.js
Normal file
39
prime.js
Normal file
@ -0,0 +1,39 @@
|
||||
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;
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user