This is in continuation to JavaScript runtime: Call Stack and Event Queue - Part 3

The setTimeout() is the JavaScript's asynchronous function. It accepts two arguments: a callback function and a time in milliseconds. The given callback function is executed after a certain amount of time, passed as the second argument, elapses.

The setTimeout(fn, 0) pushes the function, named, fn into the event queue right away (with a delay of 0 sec.) indicating that it should be executed as soon as possible. It is important to note that its execution may not start immediately as the JavaScript runtime might be busy processing the functions stored in the call stack and/or other callbacks might already be there in the event queue and waiting for their turn to get executed.

Also, the browser places all its "to-be-done" tasks, including both UI tasks and the JavaScript commands, resulting from events into a single event queue. We know that the changes made to the DOM occur instantaneously using the JavaScript commands. But to redraw (re-render) the corresponding DOM element is treated as a separate "to-be-done" task and for this a new event is created, triggered by the DOM change, which is placed at the end of the event queue.

var first = function() {
    console.log("Hello One");
var second = function () {
    setTimeout(first, 5000);    //Callback the first() after 5 secs.
    console.log("Hello Two");

Example in Detail

When the setTimeout() is invoked, there are two stack frames in the call stack and the event queue is empty. As soon as the setTimeout() is invoked, it starts native code in the browser that goes in sleep state and wait for 5 seconds. Do not assume that nothing will happen during this time period i.e. nothing is 'blocked' which means that the browser does not wait for 5 seconds and it immediately moves on executing the next line in second() function, which is the console.log().

After an elapse of 5 seconds, the native thread that slept wakes up and writes a message into the event queue with a handle to the first() function. As we know that the event loop constantly monitors whether the call stack is empty. Since the call stack is now empty, the runtime checks the event queue, it finds a message there and invokes the first() function. As a result, a new stack frame for the first() is created and pushed onto the call stack. After first() is finished executing, both the call stack and the event queue are empty again.

For Part 5, click this link: JavaScript runtime: Call Stack and Event Queue - Part 5