Web Worker Inline Test
by intrinsica
HTML
<canvas id="result" width="600"></canvas><br>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
JavaScript
/*jshint multistr: true */
var w, frames = 0, left = 0, ctx, intervalId, run=true;
function startWorker() {
var work = "var i = 0, inc = 1; \
function timedCount() { \
i = i + inc; \
if (i>580 || i<0) inc = -inc; \
postMessage(i); \
setTimeout('timedCount()', 4); \
} \
timedCount();";
var blob = new Blob([work]);
w = new Worker(window.URL.createObjectURL(blob));
intervalId = setInterval(fps, 1000);
console.log(intervalId);
w.onmessage = function(event) {
left = event.data;
};
ctx = result.getContext("2d");
run = true;
requestAnimationFrame(draw);
}
function draw() {
ctx.clearRect(0,0,result.width,result.height);
ctx.fillRect(left,40, 20,20);
frames++;
if(run)requestAnimationFrame(draw);
}
function fps() {
console.log(frames);
frames = 0;
}
function stopWorker() {
clearInterval(intervalId);
run = false;
w.terminate();
w = undefined;
}