Story Between Event Loops And Javascript, How it works?

Saniyad Chowdhury
2 min readNov 4, 2020

JavaScript is single-threaded, which means it is not able to take advantage of multithreading, we get with JAVA, C#, Python, etc. We are not given the option to run multiple processes at the same time, instead, we get a single thread to run all our processes on.

Javascript is a single threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next. It’s synchronous, but at times that can be harmful. For example, if a function takes awhile to execute or has to wait on something, it freezes everything up in the meanwhile.

A good example of this happening is the window alert function. alert(“Hello World”)

You can’t interact with the webpage at all until you hit OK and dismiss the alert. You’re stuck.

Key Concepts to Understand for the Event Loop

1. Callback Stack

2. Queue

The call stack keeps track of the order in which functions are being executed.

Picture A

function a() {
return "a"
}function b() {
return a()
}function c() {
return b()
}
c()

Picture B

Stack 
c()
b()
a()

For example, look at the two images right above. Picture A being your code and Picture B being the stack or order in which the functions are being executed. If you were to run the code on Picture A, the functions would be executed as per Picture B with c() being the first to run and a() being the last.

Queue

The queue is a list of messages that are to be processed when the time comes. Think about setTimeout() and asynchronous callbacks.

function a() {
console.log("This is function a")
}function b() {
setTimeout(function () {
console.log('this is function b')
}, 1000)
a()
}function c() {
console.log("This is function c")
b()
}
c()

Picture C

This is function c
This is function a
This is function b

Picture D

If the code in picture C was executed, you’d end up with the results shown in Picture D.

So What are Event Loops?

The event loop’s purpose is to look at the call stack and the queue. When the stack is empty, it takes the first thing on the queue and executes it. In the example I provided above referring to the queue, think about how “This is function A” is logged before “This is function B”. This is because setTimeout() set a timer on logging “This is function B”, effectively pushing it to the queue and allowing function A to execute. The event loop then saw the call stack was empty in this example, pushed the first thing on the queue, it being “This is function B” onto to the stack and then executed it.

--

--