Created
May 29, 2018 16:05
-
-
Save neopunisher/054efbd746877c1af58df94187e686c3 to your computer and use it in GitHub Desktop.
generates a web worker from a function
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(){ | |
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