What are Event Loops and What Does It Have to Do with JavaScript?

Although I became proficient in JavaScript, I realized I didn’t know what goes on in the “background” to the extent I should. I remember the first time I heard about event loops, I couldn’t wrap my head around it. However, after reading documentation and watching several videos on the topic, I decided to write a post about it for anyone who’s curious about event loops or just wants to learn more about JavaScript.

Before I say what event loops are, there are some key concepts that should be covered first. JavaScript is a single threaded programming language, meaning JavaScript can run one piece of code at a time. You might be asking yourself, but isn’t JavaScript asynchronous? While JavaScript can only run one thing at a time, it is because of the browser that allows for asynchronous behavior (such as asynchronous callbacks). With that in mind, please note that the event loop is not a part of the JavaScript engine.

Key Concepts to Understand for the Event Loop

1. Callback Stack

2. Queue

Call stack

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

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

Picture A

Stackc()
b()
a()

Picture B

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 a")
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.