Javascript’s Event Loop
Note: If you don’t know what concurrency model, processes and threads are, I found a pretty good resource which does an awesome job explaining these computer science concepts. Please, follow this link and read it before moving on.
Javascript is an event-based single-threaded programming language.
Javascript was initially created for running in internet browsers such as Firefox, Chrome, etc. In order to consume less computing resources, Javascript was made single-threaded which means that the Javascript runtime (or, in other words, “execution context”) can only execute one task at a time within a single process. In these circumstances, how would Javascript run asynchronous operations such as user-generated events like mouse clicks.
Here is where the event loop comes into play. Event loop is how the concurrency model is implemented in Javascript.
The Event Loop
Here is a visual representation of the event loop:
Here are some examples of asynchronous operations for which the event loop was created:
- user-generated events: click, drag, etc.
- HTTP requests
- Disk reads and writes
- Database reads and writes, etc.
In order to run asynchronous code, Javascript engines such as the most popular v8 engine that runs in Chrome browsers utilize the event loop architecture which consists of a stack, heap and queue.
Stack is a LIFO (“Last In First Out”) data structure which keeps track of function calls and is represented by stack frames for each function call.
Heap is a mostly unstructured memory space that allocates objects.
Queue, or message queue, or event loop queue is a FIFO (“First In First Out”) data structure that is a list of messages with associated callback functions that are processed by the event loop whenever the callback function is ready to return a result.
Let’s compare how Javascript runtime executes synchronous and asynchronous operations.
Get Wynstan’s stories in your inbox
Join Medium for free to get updates from this writer.
Here is an example of a synchronous code and the step by step description of the code execution:
function AddTwoNumbers(a, b) {
return a + b;
}
AddTwoNumbers(1, 2)Step 1: Javascript runtime creates an execution context and a process with a single thread which contains a stack and a memory heap. In this step, the function AddTwoNumbers(1, 2) gets pushed to the top of the stack where the stack frame is created for this function call. The memory heap stores the passed in parameters which are primitive values 1 and 2 as function arguments.
Step 2: The process executes the function and returns the result of the addition of two arguments which is 3 in our example.
Step 3: The stack pops the AddTwoNumbers(1, 2) stack frame off the top of the stack.
Now, let’s look at how Javascript runtime processes asynchronous operations:
function One() {
console.log("One!");
}
function Two() {
setTimeout(() => console.log("Two!"), 0);
}
function Three() {
One();
Two();
console.log("Three!");
}
Three();
One!
Three!
Two!Step 1: Function Three() gets invoked without parameters which means the function gets pushed to the top of the stack.
Step 2: Inside the function Three(), function One() gets called and pushed on top of the stack. It executes console.log(“One!”) and prints One! to the console and gets popped off the top of the stack.
Step 3: Then function Two() gets called and is pushed on top of the stack. Function Two() invokes setTimeout with a callback function that needs to be called back after 0 ms which means immediately after the current stack is empty. This callback function gets queued in the message queue in order to be processed when the current stack is empty after which the function Two() gets popped off the top of the stack.
Step 4: Then console.log(“Three!”) gets executed by being pushed onto the top of the stack. It prints Three! to the console and gets popped off the top of the stack.
Step 5: The event loop now sees that the stack is empty and checks the message queue and sees the callback function () => console.log(“Two!”). It executes it and prints Two! to the console and removes it from the top of the stack. Now, the stack is empty and the execution context gets destroyed.
In comparison with the synchronous code, Javascript runtime makes use of the message queue in order to run the asynchronous code after all the synchronous code has been executed.
ES6 Promises
The promise objects were added to the Javascript core in 2015 in order to avoid callback hell and to speed up execution of asynchronous operations.
Promises as well as their special syntax, async/await, are implemented via a job queue which is similar to the message queue except that the job queue messages are of higher priority than those of the event loop queue.
Conclusion
Asynchronous operations in Javascript are processed via the event loop which consists of a stack, heap and message queue. In 2015 with the introduction of promises, the concept of a job queue was added to the Javascript runtime architecture in order to avoid the callback hell and speed up the execution of asynchronous code.




