title: How to calculate the execution time of an async function in JavaScript?
body: <p>I would like to calculate how long an async function (<code>async</code>/<code>await</code>) is taking in JavaScript.</p>
  
  <p>One could do:</p>
  
  <pre><code>const asyncFunc = async function () {};
  
  const before = Date.now();
  asyncFunc().then(() =&gt; {
    const after = Date.now();
    console.log(after - before);
  });
  </code></pre>
  
  <p>However, this does not work, because promises callbacks are run in a new microtask. I.e. between the end of <code>asyncFunc()</code> and the beginning of <code>then(() =&gt; {})</code>, any already queued microtask will be fired first, and their execution time will be taken into account.</p>
  
  <p>E.g.:</p>
  
  <pre><code>const asyncFunc = async function () {};
  
  const slowSyncFunc = function () {
    for (let i = 1; i &lt; 10 ** 9; i++) {}
  };
  
  process.nextTick(slowSyncFunc);
  
  const before = Date.now();
  asyncFunc().then(() =&gt; {
    const after = Date.now();
    console.log(after - before);
  });
  </code></pre>
  
  <p>This prints <code>1739</code> on my machine, i.e. almost 2 seconds, because it waits for <code>slowSyncFunc()</code> to complete, which is wrong.</p>
  
  <p>Note that I do not want to modify the body of <code>asyncFunc</code>, as I need to instrument many async functions without the burden of modifying each of them. Otherwise I could just add a <code>Date.now()</code> statement at the beginning and the end of <code>asyncFunc</code>.</p>
  
  <p>Note also that the problem is not about how the performance counter is being retrieved. Using <code>Date.now()</code>, <code>console.time()</code>, <code>process.hrtime()</code> (Node.js only) or <code>performance</code> (browser only) will not change the base of this problem. The problem is about the fact that promise callbacks are run in a new microtask. If you add statements like <code>setTimeout</code> or <code>process.nextTick</code> to the original example, you are modifying the problem.</p>