Created
December 21, 2022 09:10
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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