Created
April 1, 2017 11:21
-
-
Save sdwvit/e7b0c5d2990634af1c783178800fe427 to your computer and use it in GitHub Desktop.
Spawn worker abstraction
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 spawnWorker(func) { | |
const response = `self.onmessage = () => postMessage( | |
(${func.toString()})() | |
)`; | |
const blob = new Blob([response], {type: 'application/javascript'}); | |
const worker = new Worker(URL.createObjectURL(blob)); | |
worker.onmessage = function (e) { | |
const data = e.data; | |
console.log(data); | |
}; | |
worker.run = () => worker.postMessage('start'); | |
return worker; | |
} | |
const worker = spawnWorker(() => console.log('Hello'))); | |
worker.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment