Concurrency in Javascript

Ankita Panigrahi
2 min readNov 7, 2019

--

Concurrency: It is mainly concerned with doing more than one task at a time. The tasks run virtually at the same time but not exactly. It takes advantage of CPU time-slicing where each task runs some part of it and then goes for waiting. When the first task is waiting, the CPU is assigned to the second task to complete its part of the task. To end-users, it seems the task completed simultaneously.

How does it work in Javascript?

With languages like Java, we can achieve concurrency by using many threads but javascript is a single-threaded language. It has a single call stack which executes one thing at a time.

The call stack is a data structure that records where we are in the program. It follows Last in First Out model.

Javascript works synchronously executing one thing at a time which blocks the main thread while executing. When we do some computationally expensive tasks (for eg: loops), it blocks the main thread (or the call stack). This prevents the browser from rendering the UI which may result in janky or often unresponsive user experience.

Let’s take an example:

Input:

Input:console.log(“HI”); // 1
setTimeout(function() { // 2
console.log(“There”);
}, 5000);
console.log(“JS Rocks”); // 3
Output:HI
JS Rocks
There

In the above code, setTimeout is a browser web API, not provided by the JS V8 Engine. The reason why we can do things concurrently because browsers provide us with web APIs that can be run as threads and browsers are aware of this concurrency.

As shown in the diagram below, setTimeout is a part of web APIs and when it is completed i.e in this case after 5 secs (or 5000 ms), it will get pushed to task queue (callback queue) and then comes the event loop

Event loop diagram

An event loop has a simple task of looking at the call stack and task queue. If the call stack is empty, it will push the events in task queue to call stack. In the above code, statements 1 & 3 will go to the call stack and statement 2 would be a web API that will be put into task queue after it gets completed. So the event loop will see that the call stack executes statements 1 & 3 and then look up the task queue, put it into call stack (when empty) and executes it.

Note: If the code has many asynchronous or slow tasks, then it can block the event loop because once one task goes to the call stack it will take its time and then the event loop will be blocked for another one.

--

--

Ankita Panigrahi
Ankita Panigrahi

No responses yet