deb-novnc/prime.js
Joel Martin d628147bca 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.
2010-04-10 15:52:27 -04:00

40 lines
911 B
JavaScript

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;
}
}