title: Javascript: avoid eager async execution and prioritize calls on event loop
body: <p>My Javascript app needs to do some heavy calculations on the UI thread (let's ignore web workers for the scope of this question).<br>
  Luckily, the work to be done is embarrassingly parallel and can be cut into thousands of small async functions.</p>
  
  <p>What I would like to do is: Queue up all these async functions on the event loop, but prioritize UI events.<br>
  If this works, the impact on UI responsiveness should be very low. Each of the functions takes only a few milliseconds.</p>
  
  <p>The problem is that Javascript eagerly executes async code. Until you run into something like <code>await IO</code> it simply executes all the code as if it was synchronous.</p>
  
  <p>I would like to break this up: When the execution encounters an async call, it should put it on the event loop but before executing it, it should check if there's a UI event waiting to be processed.<br>
  Basically, I'm looking for a way to immediately <code>yield</code> from my worker functions, without returning a result.</p>
  
  <p>I've experimented and found a workaround. Instead of calling the async function directly, it can be wrapped in a timeout. This is pretty much exactly what I wanted: The async call is not executed but queued up on the event loop.<br>
  Here is a simple example, based on react. After clicking, the button will update immediately, instead of waiting for all those calculations to finish.<br>
  (The example probably looks like horrible code, I'm putting heavy calculations inside the render function. But that's just to keep it short. It really doesn't matter where the async functions are kicked off, they always block the single UI thread):</p>
  
  <pre><code>// timed it, on my system it takes a few milliseconds
  async function expensiveCalc(n: number) {
    for (let i = 0; i &lt; 100000; i++) {
      let a = i * i;
    }
    console.log(n);
  }
  
  const App: React.FC = () =&gt; {
    const [id, setId] = useState("click me");
  
    // many inexpensive calls that add up
    for (let i = 0; i &lt; 1000; i++) {
      setTimeout(() =&gt; expensiveCalc(i), 1);
    }
  
    // this needs to be pushed out as fast as possible
    return (
      &lt;IonApp&gt;
        &lt;IonButton
          onClick={() =&gt; setId(v4())}&gt;
          {id}
        &lt;/IonButton&gt;
      &lt;/IonApp&gt;
    );
  };
  </code></pre>
  
  <p>Now, this looks neat. The synchronous execution of the render function is never interrupted. All the calculation functions are queued up and done after render is finished, they don't even have to be async.</p>
  
  <p>What I don't understand is: This works even if you click on the button many times!
  My expectation would be that all calls on the event loop are treated equally. So the first time the render should be instant, the second time it needs to wait for all the timeouts to be executed first.<br>
  But what I see is:</p>
  
  <ul>
  <li>click on the button -> text updated</li>
  <li>immediately click on the button again -> text updated</li>
  <li>look at console logs: it counts up to 1000, then starts back at 0 and counts up to 1000 again.</li>
  </ul>
  
  <p>So the event loop does not execute in-order. And somehow UI events are prioritized. That's awesome. But how does it work? And can I prioritize events myself?</p>
  
  <p><a href="https://codesandbox.io/s/funny-clarke-w4knp?file=/sandbox.config.json" rel="nofollow noreferrer">Here's a sandbox where you can play around with the example.</a></p>