Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@neopunisher
Created May 29, 2018 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neopunisher/054efbd746877c1af58df94187e686c3 to your computer and use it in GitHub Desktop.
Save neopunisher/054efbd746877c1af58df94187e686c3 to your computer and use it in GitHub Desktop.
generates a web worker from a function
(function(){
function aWorker(){
onmessage = function(e) {
console.log('Message received from main script');
var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
console.log('Posting message back to main script');
postMessage(workerResult);
}
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout(timedCount,500);
}
timedCount();
}
function fn2workerURL(fn) {
var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'})
return URL.createObjectURL(blob)
}
var worker = new Worker(fn2workerURL(aWorker));
worker.postMessage('hello')
worker.onmessage = function(oEvent) {
console.log('Received: ' + oEvent.data);
};
worker.onerror = function(err) {
console.error(err);
};
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment