Skip to content

Instantly share code, notes, and snippets.

@park-brian
Last active November 8, 2018 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save park-brian/0719c182db481a6a469c626ff9181128 to your computer and use it in GitHub Desktop.
Save park-brian/0719c182db481a6a469c626ff9181128 to your computer and use it in GitHub Desktop.
Runs a function in a web worker

Make sure the Content Security Policy allows access to scripts that have been created on the same origin (eg: this will not work in the gists developer console since script-src is set to assets-cdn.github.com)

function sum(arr) {
    return arr.reduce(function(a, b) { return a + b; });
}

var sumWorker = workerFn(sum);

// generate input
for(var input = []; input.length < 1000; input.push(input.length));

sumWorker(input).then(function(result) { console.log(result); });   
function workerFn(fn) {
return function () {
var args = [].slice.call(arguments);
return new Promise(function (resolve, reject) {
// wrap function in onmessage/postMessage
var workerScript = 'self.onmessage = function(e) {' +
'postMessage((' + fn.toString() + ').apply(null, e.data));' +
'self.close();' +
'}';
// create worker from object url
var objectUrl = URL.createObjectURL(new Blob([workerScript]));
var worker = new Worker(objectUrl);
worker.onmessage = function(e) {
URL.revokeObjectURL(objectUrl);
resolve(e.data);
};
worker.onerror = function(e) {
URL.revokeObjectURL(objectUrl);
reject(e);
};
worker.postMessage(args);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment