Created
June 24, 2013 12:21
-
-
Save SunboX/5849664 to your computer and use it in GitHub Desktop.
Create web workers without a separate worker JS files.
Source: http://jsbin.com/owogib/8/
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
function worker() { | |
setInterval(function() { | |
postMessage({foo: "bar"}); | |
}, 1000); | |
} | |
var code = worker.toString(); | |
code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}")); | |
var blob = new Blob([code], {type: "application/javascript"}); | |
var worker = new Worker(URL.createObjectURL(blob)); | |
worker.onmessage = function(m) { | |
console.log("msg", m); | |
}; |
looks very good
Thank you for this example. Little mistake: worker function and worker object names intersection.
In addition for this.
If you use webworkers for short tasks, you should release them by calling close(), see example here https://jsfiddle.net/bdjv0u4g/
Otherwise you will get a thread leak.
@AlekseyPi lol actually he's conserving memory. That worker function wasn't needed, as it was converted to a blob. It was no longer needed. No need to create extra variables.
Also, GC cleans up Workers, but yes, recommended to close that aswell.
and NOT just for shorter (Tasks), but for all.
thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
helpful a lot on right time! Thx!