Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spawn worker abstraction
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