title: How to queue a microtask if the browser doesn't support native Promises?
body: <p>It's better to write code that doesn't rely on the timing of immediate callbacks (like microtasks vs macrotasks), but let's put that aside for the moment.</p>
  
  <p><code>setTimeout</code> queues a macrotask, which, at a minimum, waits to start until all microtasks (and microtasks that they spawn) finish. Here's an example:</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>console.log('Macrotask queued');
  setTimeout(function() {
    console.log('Macrotask running');
  });
  Promise.resolve()
    .then(function() {
      console.log('Microtask running');
    });
  console.log('Microtask queued');
  console.log('Last line of script');</code></pre>
  </div>
  </div>
  </p>
  
  <p>The behavior of a <code>.then</code> on a resolved Promise is fundamentally different from the behavior of an immediate <code>setTimeout</code> callback - the Promise <code>.then</code> will run first, even if the <code>setTimeout</code> was queued first. But only modern browsers support Promises. How can the <em>special</em> functionality of a microtask be properly polyfilled if <code>Promise</code> doesn't exist?</p>
  
  <p>If you try to imitate a <code>.then</code>'s microtask by using <code>setTimeout</code>, you'll be queuing a macrotask, not a microtask, so the badly-polyfilled <code>.then</code> won't run at the right time if a macrotask is already queued.</p>
  
  <p>There's a solution using <code>MutationObserver</code>, but it looks ugly, and isn't what <code>MutationObserver</code> is for. Also, <code>MutationObserver</code> is not supported on IE10 and earlier. If one wants to queue a microtask in an environment that doesn't natively support Promises, are there any better alternatives?</p>
  
  <p>(I'm not <em>actually</em> trying to support IE10 - this is just a theoretical exercise on how microtasks can be queued without Promises)</p>