JS : The Illusion of multi-threading

Rohit Satwadhar
2 min readDec 26, 2021

--

Event Loop

JS as a language is a single threaded, asynchronous language. What that means is that JS can only process one job at a time. This sounds like a big pitfall when we consider multi threaded languages like java which can perform multiple jobs in parallel. Then if JS has such a big issue how come node.js is so famous? The reason is Event loop and smart use of data structures. Event loops gives users a illusion of multi-threading.

Let’s see what is event loop. For that let’s talk about some data structures first.

  1. Call Stack : It is common knowledge that calls to various functions are stored in call stack. And functions are pushed and popped into this stack for processing.
Call Stack

2. Event Queue : This queue holds functions that need to processed. This pushes functions on the call stack.

Event Queue

3. Browser API : Browser APIs (or web APIs) are the APIs that come built-in with the browsers. They allow developers to perform complex operations without dealing with the sophisticated lower-level code.

Now let’s talk about how async request are handled by node.js. One of the most known async call is setTimeOut(). This takes a time interval and a callback function that needs to be called after that time interval.

When this call is first processed in call stack. This is sent out to Browser API. And call stack moves on to next function on stack. It’s now Browser’s job to wait for the specified time interval. Browser API creates a new thread to process this setTimeout() and when task is finished on that thread callback function provided is pushed to event queue by the browser API and then that callback is eventually pushed to call stack where it is processed as a normal function call.

Event Loop

Now if you properly observe the behavior you can see that function completed on full loop in the flow. It first started from call stack and then came back to it. Hence a event loop.

--

--

Rohit Satwadhar
Rohit Satwadhar

Written by Rohit Satwadhar

I Write about new things that I learn. That is how I remember stuff. These things are mostly tech related.