Skip to content

Instantly share code, notes, and snippets.

@eswak
Created December 21, 2022 09:10
Show Gist options
  • Save eswak/eae48aa6bb7e99f6daf556c9c833579e to your computer and use it in GitHub Desktop.
Save eswak/eae48aa6bb7e99f6daf556c9c833579e to your computer and use it in GitHub Desktop.
Easily run a function in a background worker, out of the main UI thread.
function offthread(fn, args, cb) {
var blob = new Blob(
[
'var fn = ' + fn.toString() + ';',
'var ret = fn.call(null, ...' + JSON.stringify(args) + ');',
'postMessage(ret);'
],
{ type: 'text/javascript' }
);
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function (e) {
cb && cb(e.data);
worker.terminate();
};
}
var start = Date.now();
offthread(
function (nIterations) {
var n = 0;
for (var i = 0; i < nIterations; i++) {
n++;
}
return n;
},
[1e9],
function (n) {
console.log('Completed', n, 'iterations offthread in', Date.now() - start, 'ms.');
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment