JavaScript: Under the Hood

Recently, I was on a technical decision call to discuss about few implementation details.

We have a frontend component which should change its state when a condition is met in the backend. The constraint was the inability for the backend to send notifications to the frontend.

My tech lead suggested that we can use polling from the frontend.

My immediate intuition was that polling is inherently bad and it would consume lot of resources in the user’s browser. But I didn’t have any arguments for backing up with this intuition.

When I said this, he proclaimed that it wasn’t the case due to the asynchronous nature of JavaScript and event loop.

Most of my work was in backend systems, I realized that I didn’t clearly understand how JavaScript, a single-threaded language, can be performant and asynchronous.

This question lead into a small tangential rabbit-hole, which I found quite interesting. Here’s my attempt to present it.

Call-Stacks and Program Execution

Program execution happens through call-stacks. As program executes, instructions are added to the stack. Once they are processed they are popped off. If an instruction crashes the program, you can clearly see the path which caused the crash, the path being Stack Trace.

JS Stack Trace

In a single-threaded system, there is only one main thread i.e we can only process one instruction at a time, which means we only have one call-stack.

Not all instructions can be completed quickly. Certain processes might take a long time to complete, for example: processing of images, running ML models etc.

With the single-threaded constraint, these instructions will essentially block the program execution. It is bit more problematic in the browser, which will freeze for the user, not allowing them to do any sort of action.

Hence, we need a way to execute these instructions asynchronously i.e doesn’t block the other instructions.

We can spin off the processing of this blocking instruction in a different thread.

Asynchronous Processing

Wait, how can JS, a single-threaded language, spin off processing of instruction in a different thread?

Short Answer: It doesn’t.

Long Answer: the v8 engine, the javascript interpreter is single threaded. But, the browser exposes powerful APIs which can allow us to spin off and run asynchronous processes.

The question now becomes: How can any async process communicate to the main thread the result of the computation?

There are few ways:

  1. Emitting events → On processing, the subprocess can emit events.
  2. Callback method → Once done, the callback method is called with the arguments passed.

At this instance, they seemed to have used the callback method. The callback cannot hijack the call-stack immediately, that would delay the processing of other instructions.

This is where a common productivity pattern comes in: The Pull System. Instead of directly processing the response/adding it directly to the call-stack, the results are added to the Callback queue, which is an intermediate queue.

At a regular interval, the event-loop checks if the call-stack is empty. If the call-stack is empty, the first task from the callback-queue is picked up and added to the call-stack.

Why is polling not resource-intensive?

Coming back to the initial question of “how can polling not be resource intensive?”

Let’s consider the following code:


function pollBackend(currentState) {
// Check the state with backend
// simulating inProgress to completed state
console.log("current state", currentState)
if (currentState % 5 === 0){
console.log("Done");
} else {
setTimeout(pollBackend, 1, currentState + 1);
}
}
let initialState = 1;
pollBackend(initialState);

Let’s say we check at some regular interval, every second. We call the pollBackend method, which checks with the backend if a process has completed.

Here’s the initial call-stack

Call Stack

setTimeout is an API method provided by the browser, which is processed asynchronously.

Once setTimeout is completed, the callback method is added to the callback queue.

Callback Queue

Once the call-stack is empty, event-loop adds the callback method to the call-stack.

Event Loop

The main thread doesn’t process the callback method until the call-stack is empty i.e idle state. We don’t clog the callback-queue, the method self propagates only until it reaches the terminal state.

---

References

  1. Philip Roberts has an amazing talk in JSConf. I have just imitated him in this blog post. The illustrations are also from the Loupe tool, which was graciously created by him to visualize the working of JS under the hood.