title: Why does the UI not update for async functions in javascript
body: <p>I have a browser application where I want to change some text in the UI to say that the page is loading, then run a long process, and once the process is complete to say that the page is finished loading.  </p>
  
  <p>Using the code written below I can get this to work when I call <code>ProperlyUpdatesUIAsync</code>, where the text is changed while the long process is running, and then once the long process is complete, it changes again to indicate that it is done.  </p>
  
  <p>However, when I use the <code>DoesNotUpdateUIUntilEndAsync</code> method, the UI does not get updated until after the long process is finished, never showing the "loading" message.  </p>
  
  <p>Am I misunderstanding how <code>async</code>/<code>await</code> works with JavaScript?  Why does it work in the one case but not in the other?</p>
  
  <pre><code>async function ProperlyUpdatesUIAsync(numberOfImagesToLoad) {
      $("#PageStatusLabel").text("Loading..");
  
      await pauseExecutionAsync(2000);
  
      $("#PageStatusLabel").text("Loaded");
  }
  
  // this method doesn't do anything other than wait for the specified
  // time before allowing execution to continue
  async function pauseExecutionAsync(timeToWaitMilliseconds) {
      return new Promise(resolve =&gt; {
          window.setTimeout(() =&gt; {
              resolve(null);
          }, timeToWaitMilliseconds);
      });
  }
  
  
  async function DoesNotUpdateUIUntilEndAsync(numberOfImagesToLoad) {
      $("#PageStatusLabel").text("Loading..");
  
      await runLongProcessAsync();
  
      $("#PageStatusLabel").text("Loaded");
  }
  
  async function runLongProcessAsync() {
      // there is a for loop in here that takes a really long time
  }
  </code></pre>
  
  <p><strong>Edit:</strong>
  I experimented with a few things and this new refactor is giving me the desired result, but I do not like it.  I wrapped the long running loop in a setTimeout with a timeout setting of 10.  With a value of 10, the UI is updated before running the loop.  However, a value of 0 or even 1 does not allow the UI to update, and it continues to behave as if the timeout was not declared at all.  10 seems so arbitrary.  Can I really rely on that working in every scenario?  Shouldn't async/await defer execution until the UI is updated without my having to wrap everything in a timeout?</p>
  
  <pre><code>async function runLongProcessThatDoesNotBlockUIAsync() {
      return new Promise(resolve =&gt; {
          window.setTimeout(() =&gt; {
      // there is a for loop in here that takes a really long time
              resolve(null);
          }, 10);
      });
  }
  </code></pre>