Skip to content

Instantly share code, notes, and snippets.

@tbtlr
Created May 14, 2012 12:57
Show Gist options
  • Save tbtlr/2693804 to your computer and use it in GitHub Desktop.
Save tbtlr/2693804 to your computer and use it in GitHub Desktop.
How to implement synchronous(ish) Web Worker tasks in Firefox, using JS1.7 Generators.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script type="application/javascript;version=1.7">
var worker = new Worker('worker.js');
var g;
worker.onmessage = function (e) {
g.send(e.data);
};
function fibonacci(num) {
// Fibonacci code shameless copied from https://gist.github.com/986590. Thanks!
worker.postMessage('(function(n){for(var a=0,b=1;n--;)b=a+(a=b);return a}(' + num + '))');
}
function sleep(ms) {
worker.postMessage('var n=+new Date;while(+new Date-n<' + ms + ');');
}
function main() {
console.log('Calculating fibonacci of 40...');
var f = yield fibonacci(40);
console.log('Done. Result: ' + f);
console.log('Going to sleep for 5 seconds...');
yield sleep(5000);
console.log('Done.');
yield;
}
g = main();
g.next();
</script>
</body>
</html>
onmessage = function(e) {
postMessage(eval(e.data));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment