Skip to content

Instantly share code, notes, and snippets.

@tdr2d
Last active August 24, 2018 14:00
Show Gist options
  • Save tdr2d/a84496bf972ed2b88cc507a77ff19606 to your computer and use it in GitHub Desktop.
Save tdr2d/a84496bf972ed2b88cc507a77ff19606 to your computer and use it in GitHub Desktop.
Run a function into a web worker instance
/**
* @argument callback function
* @argument arg argument
* @argument onMessageCallback function
* usage: runInWorker(function(e){return JSON.parse(e);}, '{"name": "toto"}', console.log);
**/
function runInWorker(callback, arg, onMessageCallback){
var blob = new Blob(['onmessage=function(_e){postMessage('+ callback.toString() + '(_e)); close();']);
var worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = onMessageCallback;
worker.postMessage(message)
return worker;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment