Estoy trabajando en una biblioteca JS que potencialmente puede realizar cálculos largos, congelando el hilo principal. Conozco Web Workers y también se usarán, pero me gustaría asegurarme de que el código también se pueda ejecutar en el subproceso principal sin bloquearlo.
Probé la siguiente solución para dividir cálculos largos en partes más pequeñas:
const performLongComputations = () => { let sum = 0; for (let i = 0; i < 10_0000; ++i) { sum += Math.random(); } }; const synchronousExecution = () => { let totalTime = 0; for (let i = 0; i < 1_000; ++i) { const startTime = performance.now(); performLongComputations(); totalTime += performance.now() - startTime; } return totalTime; }; console.log(`Synchronous execution took ${synchronousExecution()} ms`); const asynchronousExecution = () => new Promise(resolve => { let totalTime = 0; let currentIteration = 0; const start = () => { const startTime = performance.now(); performLongComputations(); totalTime += performance.now() - startTime; if (currentIteration++ < 1_000) { setTimeout(start, 0); } else { resolve(totalTime); } }; start(); }); asynchronousExecution().then(time => console.log(`Asynchronous execution took ${time} ms`));En Chrome, la salida es la siguiente:
Synchronous execution took 837.0999999996275 ms Asynchronous execution took 2853.699999993667 msEn Firefox:
Synchronous execution took 9674 ms Asynchronous execution took 9203 msProbado en Linux, Chrome 92.0.4515.107, Firefox 90.0.
Hay dos cosas que me sorprenden: