by tantalor · 11y ago · 0 comments
var code = "onmessage = function (evt) {evt.data.sort(); postMessage(evt.data)}";
function asyncSort(data, cb) {
var worker = new Worker(URL.createObjectURL(new Blob([code])));
worker.onmessage = function (evt) { cb(evt.data); };
worker.postMessage(data);
}
Example, asyncSort([3, 2, 1], function (res) { console.log(res); });
Prints, "[1, 2, 3]"However it looked like he needed to support IE8, so this might be an ok solution (although I would argue a terrible one for anyone who doesn't need to support IE8/9).
> when transferring an ArrayBuffer from your main app to Worker, the original ArrayBuffer is cleared and no longer usable
This is really too restrictive in many situations.
[1] https://developers.google.com/web/updates/2011/12/Transferab...
Depending on what you're doing, you may want to yield after x operations rather than on every recursive invocation like the example shown. There is a performance cost to using setImmediate.
But FWIW, you can do canvas pixel operations with a web worker, which you then blit to the canvas, which is acceptable in some cases.
Edit: I assume I'm being downvoted because you're still running the script in the main thread, and therefore lose the concurrency. Obviously this is an issue with a polyfill, but the point of polyfilling web workers would be to keep the one codebase rather than writing your your web app with and then without web workers.