order of execution of node JS timer APIs

I am very new to node.js. Am trying to understand what exactly is meant by 'asynchronous' in terms of node js.

In the above context I have the below code:-

function foo()
{
  setImmediate(function two()
  {
    console.log(1);
  });
  setTimeout(function one()
  {
    console.log(3);
  },0);
  process.nextTick(function three()
  {
    console.log(2);
  });
  console.log(4);
}
foo();

can some one please explain me, in depth, as to what exactly would be the order of execution for all of the above timer APIs and WHY will it be so? Any explanations/references regarding the call back stack etc. will also be helpful.

First of all, 4 gets logged first because all other calls to setImmediate, setTimeout or nextTick delay the execution of a function to somewhere after the currently executing code. But they all do it differently:

setTimeout This function allows you to do something after a specific amout of milliseconds. If the milliseconds you pass to this function are less that 1ms, it will always wait 1ms before calling your function.

setImmediate This function allows you to do something after node has processed all i/o events. Node processes i/o events in every cycle of the event queue. So setTimeout will always execute your function in the next cycle of the event queue. This allows the queue spin unblocked.

process.nextTick This function allows you to do something immediately after the currently running code finishes. You can imagine it like you would be able to modify the currently executing code and add some lines after it, so that it does something more before it's finished. Calling this function again and again does block the event loop because it cannot go on to the next task in the queue, since it's still busy with the current one. This means, node does not process the i/o events until the last function you passed to nextTick got executed. Therefore you should never call this function recursively or use it too much, because it can stop the event loop from spinning. Node will display a warning if this happens, though.

So.. to explain the output of 4 2 1 3:

  1. 4 is the first log that's not getting delayed and thus is the first output.

  2. 2 is getting logged immediately after foo() finishes and thus is the second

  3. 3 is faster than 1 because a usual event loop cycle is much faster than 1 millisecond, and so.. 3 is the third log

  4. setTimeout delays by at least 1ms which is the longest delay of all the delay functions. It's clearly the last.