title: Breaking long JS calculations up into pieces - strange Chrome behaviour
body: <p>I'm working on a JS library that can potentially perform long computations, freezing the main thread. I know about Web Workers and they will be used as well, but I would like to ensure that the code can also be executed on the main thread without blocking it.</p>
  <p>I've tried the following solution to break long computations up into smaller pieces:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const performLongComputations = () =&gt; {
      let sum = 0;
      for (let i = 0; i &lt; 10_0000; ++i) {
          sum += Math.random();
      }
  };
  
  const synchronousExecution = () =&gt; {
      let totalTime = 0;
      for (let i = 0; i &lt; 1_000; ++i) {
          const startTime = performance.now();
          performLongComputations();
          totalTime += performance.now() - startTime;
      }
      return totalTime;
  };
  
  console.log(`Synchronous execution took ${synchronousExecution()} ms`);
  
  const asynchronousExecution = () =&gt; new Promise(resolve =&gt; {
      let totalTime = 0;
      let currentIteration = 0;
  
      const start = () =&gt; {
          const startTime = performance.now();
          performLongComputations();
          totalTime += performance.now() - startTime;
  
          if (currentIteration++ &lt; 1_000) {
              setTimeout(start, 0);
          } else {
              resolve(totalTime);
          }
      };
  
      start();
  });
  
  asynchronousExecution().then(time =&gt; console.log(`Asynchronous execution took ${time} ms`));</code></pre>
  </div>
  </div>
  </p>
  <p>In Chrome, the output is as follows:</p>
  <pre><code>Synchronous execution took 837.0999999996275 ms
  Asynchronous execution took 2853.699999993667 ms
  </code></pre>
  <p>In Firefox:</p>
  <pre><code>Synchronous execution took 9674 ms
  Asynchronous execution took 9203 ms
  </code></pre>
  <p>Tested on Linux, Chrome 92.0.4515.107, Firefox 90.0.</p>
  <p>There are two things that surprise me:</p>
  <ol>
  <li>Why such a difference between sync and async code execution times in Chrome?</li>
  <li>Why is asynchronous code usually faster on FF?</li>
  </ol>