4 ms·
For anyone that is interested in easily using WebWorkers for this sort of work please check out task.js (https://github.com/icodeforlove/task.js https://github.
by chadscira 10y ago
For anyone that is interested in easily using WebWorkers for this sort of work please check out task.js (https://github.com/icodeforlove/task.js https://github.com/icodeforlove/task.js).
It allows you to send a pure function with provided arguments to a autoscaling WebWorker pool.
Heres a similar demo (http://s.codepen.io/icodeforlove/debug/ZOjBBB http://s.codepen.io/icodeforlove/debug/ZOjBBB , you can bring all cores to 100% usage)
But for this specific scenario it could have been coded like this using task.js (vs http://afshinm.github.io/50k/worker.js http://afshinm.github.io/50k/worker.js which is not reusable)
// mentioned sort function (close to exact code from site)
function bubbleSort(a) {
var swapped;
do {
swapped = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
} while (swapped);
return a;
}
// turn the function into a worker task
const bubbleSortAsync = task.wrap(bubbleSort);
// this now runs in a autoscaling worker pool (first run includes worker initialization time)
console.time('BubbleSort Worker');
bubbleSortAsync([9,1,2,3]).then(sortedArray => {
console.timeEnd('BubbleSort Worker');
}, error => { /* this is extra credit, yes we can handle worker errors */ });
Also when dealing with large messages you can use transferables (https://developer.mozilla.org/en-US/docs/Web/API/Transferable https://developer.mozilla.org/en-US/docs/Web/API/Transferabl...).
The web has really came a long way, this kind of stuff is extremely useful, for instance you could use it when processing pixel data for a 10MP image with a RGBA array of 40M. In that scenario the work can be spread across all cores, and blows away the alternate approach of just locking the UI. In that case if you were using task.js you would just chunk the work, and use a async control flow library like bluebird.
// in this situation all cores would be at 100% without locking the UI
let processedPixels = await Promise.map(chunks, processPixelChunkAsync);