title: Callback queue ordering of Node js
body: <p>Example 1:</p>
  
  <pre><code>console.log('Starting app');
  
  setTimeout(() =&gt; {
    console.log('callback 1');
  }, 2000);
  
  sleep(4000);
  
  setTimeout(() =&gt; {
    console.log('callback 2');
  }, 1000);
  
  console.log('Finishing up');
  
  function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i &lt; 1e7; i++) {
      if ((new Date().getTime() - start) &gt; milliseconds){
        break;
      }
    }
  }
  
  //Its Output
  Starting app
  Finishing up
  Callback 1
  Callback 2
  </code></pre>
  
  <p>Example 2 :</p>
  
  <pre><code>console.log('Starting app');
  
  setTimeout(() =&gt; {
    console.log('callback 1');
  }, 2000);
  
  sleep(4000);
  
  setTimeout(() =&gt; {
    console.log('Callback 2');
  }, 0);
  
  console.log('Finishing up');
  
  function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i &lt; 1e7; i++) {
      if ((new Date().getTime() - start) &gt; milliseconds){
        break;
      }
    }
  }
  
  //Its Output
  Starting app
  Finishing up
  Callback 2
  Callback 1
  </code></pre>
  
  <p>I am trying to understand that two asyncs function timer start executing simultaneously or one by one.<br>
  <code>Example 1</code> is working fine as i expected. Callback 1 reached in queue first because it has timeout of 2 seconds. because there delay is for 4 seconds before the Callback 2.</p>
  
  <p><code>Example 2</code> this example is not working as i expected. Callback 1 should be reached in queue first because it has timeout of 2 seconds and delay of 4 seconds before the Callback 2.</p>