4 ms·
Your last snippet only defers the code execution to the next iteration of the event loop. If it's synchronous, Since it's "blocking" anyways (no IO or network r
by arilotter 8y ago
Your last snippet only defers the code execution to the next iteration of the event loop. If it's synchronous, Since it's "blocking" anyways (no IO or network requests), why not just `let result = collection.map(expensiveFunction)` ?
- dvlsg 8y agoYou could toss the expensive function in a web worker to make it non blocking.
- Waterluvian 8y agoToo expensive to do in one frame. Too cheap to use a worker. Alas. :)
- Klathmon 8y agoDepending on the data you are sending transferrable objects could be your solution. Typed arrays can be zero-copy transferred to a worker extremely quickly, modified, then transferred back if needed. No costly copying or cloning needed. But it won't work with just objects, just typed arrays.
- Waterluvian 8y agoYep. In my example I want each iteration of map to be queued so they all occur whenever there isn't rendering or whatnot to be done.
- chrismorgan 8y agoI was making the assumption that it was completely synchronous, and thus that using a new setTimeout per item wouldn’t be helpful, but I neglected to consider UI responsiveness—and so on reflection such a thing might be useful. Taking that into account, it becomes rather messier: new Promise(resolve => { const out = []; const iterator = collection[Symbol.iterator](); function next() { const item = iterator.next(); if (item) { setTimeout(() => { out.push(expensiveFunction(item.value)); next(); }); } else { resolve(out); } } next(); }); JavaScript’s threading model is rather hostile to expensive CPU-bound functions. Workers are just too hard to use unless you go all in with that architecture. I love being able to work with things like Rayon in Rust.