Created
May 14, 2012 12:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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