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:
Joel Martin
2010-04-10 15:52:27 -04:00
parent 85b7a7d411
commit d628147bca
2 changed files with 79 additions and 0 deletions
+39
View 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;
}
}