Skip to content

Instantly share code, notes, and snippets.

@TheGreatRambler
Last active March 24, 2018 17:47
Show Gist options
  • Save TheGreatRambler/f61c83e23ce0b93d4eeb2fe0c8ad1659 to your computer and use it in GitHub Desktop.
Save TheGreatRambler/f61c83e23ce0b93d4eeb2fe0c8ad1659 to your computer and use it in GitHub Desktop.
A function that can be used to run functions in web workers
// Function that can run a function supplied in a web worker
// MIT License Copyright TheGreatRambler
// Free to use
function runInWebWorker(func, argsarray, callback) {
// func: function to use
// argsarray: the arguments to pass
// callback: the callback function
var blobdata = 'var returnstatement=(' + func.toString() + ')(' + argsarray.join(",") + ');self.postMessage(returnstatement);self.close();';
console.log(blobdata);
var blobURL = URL.createObjectURL(new Blob([blobdata], {
type: 'application/javascript'
}));
workertouse = new Worker(blobURL);
URL.revokeObjectURL(blobURL);
workertouse.onmessage = function(e) {
callback(e.data);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment