Abhinav Rai

JS Under the hood

Well JS runs on a single thread. Wait, then how does all the async operations happen. Well they happen on the someone’s else thread.

Everything runs on a different thread except our code.

Lets see an example —

Synchronous implementation (python) :

import requests
r = requests.get('http://abhinavrai.com')
print r.text
print "I come after the request"

Async implementation (js) :

var request = require('request');
request('http://abhinavrai.com', function (error, response, body) {
  console.log(body);
})
console.log('I come after the request');

Whats a Call stack?

Any function which is to be executed is sent to the call stack. If it makes a call to another function, then the function is pushed in the stack. Thats why we are able to get the stack trace of error when anything goes wrong.

Now when it sees any operation which takes some time (timeout, network call, I/O) it moves the function to the Event table.

What is Event Table?

This is a data structure which knows that a certain function should be triggered after a certain event. Once that event occurs (timeout, click, mouse move) it sends a notice. This does not execute the event. It sends it to Event Queue.

What is Event Queue / Message Queue?

This queue receives the events from the event table and waits to be sent to the call stack for execution.

What is Event Loop?

The infamous event loop of js is takes message from this queue and puts it to call stack. But only after whatever the call stack is doing is finished.

What is SetImmediate?

The Node.js setImmediate function interacts with the event loop in a special way. Any function passed as the setImmediate() argument is a callback that’s executed in the next iteration of the event loop.

How is setImmediate() different from setTimeout(() => {}, 0)(passing a 0ms timeout), and from process.nextTick()? A function passed to process.nextTick() is going to be executed on the current iteration of the event loop, after the current operation ends. This means it will always execute before setTimeout and setImmediate. A setTimeout() callback with a 0ms delay is very similar to setImmediate(). The execution order will depend on various factors, but they will be both run in the next iteration of the event loop.

What is process.nextTick()?

In Node.js, each iteration of an Event Loop is called a tick. To schedule a callback function to be invoked in the next iteration of the Event Loop, we use process.nextTick(). It just takes a callback with no time bound, since it will be executing in the next iteration of the Event Loop.

Read https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ for a detailed read on the event loop and how the things are scheduled.

You may contact the author at me@abhinavrai.com