title: understanding the node.js event queue and process.nextTick
body: <p>I'm having trouble understanding exactly how <code>process.nextTick</code> does its thing. I thought I understood, but I can't seem to replicate how I feel this should work:</p>
  
  <pre><code>var handler = function(req, res) {
      res.writeHead(200, {'Content-type' : 'text/html'});
      foo(function() {
          console.log("bar");
      });
      console.log("received");
      res.end("Hello, world!");
  }
  
  function foo(callback) {
      var i = 0;
      while(i&lt;1000000000) i++;
      process.nextTick(callback);
  }
  
  require('http').createServer(handler).listen(3000);
  </code></pre>
  
  <p>While <code>foo</code> is looping, I'll send over several requests, assuming that <code>handler</code> will be queued several times behind <code>foo</code> with <code>callback</code> being enqueued only when <code>foo</code> is finished.</p>
  
  <p>If I'm correct about how this works, I assume the outcome will look like this:</p>
  
  <pre><code>received
  received
  received
  received
  bar
  bar
  bar
  bar
  </code></pre>
  
  <p>But it doesn't, it's just sequential:</p>
  
  <pre><code>received
  bar
  received
  bar
  received
  bar
  received
  bar
  </code></pre>
  
  <p>I see that <code>foo</code> is returning before executing <code>callback</code> which is expected, but it seems that <code>callback</code> is NEXT in line, rather than at the end of the queue, behind all of the requests coming in. Is that the way it works? Maybe I'm just not understanding how exactly the event queue in node works. And please don't point me <a href="http://howtonode.org/understanding-process-next-tick">here</a>. Thanks.</p>