Hello, everybody!
Today, as the title says ?, I’ll be talking about the event loop.
This is not a topic that interviewers often ask about directly (I can only remember two occasions when they asked me to explain the event loop). BUT, in most interviews, they ask questions that are related to it. For example:
All those questions are much easier to answer if you understand how the event loop works.
I'll be honest: this topic isn’t my favorite. I much prefer questions about the behavior of code rather than explaining how the event loop works for 10 minutes straight.?
Let’s dive in! ?
## Questions
1. What is the event loop?
2. Examples
Short Answer:
The event loop is responsible for handling asynchronous tasks in the JavaScript runtime.
To be honest, I don’t think this answer is enough to satisfy the curiosity of an interviewer asking about the event loop. So, in this post, I’d like to dive deeper into this topic.
More than just knowing the concepts, it’s important to understand how it works. That’s why I’ve added some examples at the end.
JavaScript has a runtime based on an event loop, which is responsible for handling tasks. Each language has a unique runtime, and an important point to note is that JavaScript is single-threaded.
Single-threaded means that JavaScript can handle only one task at a time. This is why the event loop is so essential in JavaScript; it helps manage tasks efficiently despite this single-thread limitation.
To understand the event loop better, let’s first look at its main components:
The call stack is a data structure that keeps track of the functions we call. You can think of it like a stack of plates: when a function is called, it’s added to the stack, and when it finishes, it’s removed from the stack.
The call stack operates on a LIFO (Last-In-First-Out) principle, meaning JavaScript executes functions in the order they’re stacked—from the topmost item down to the bottom, one at a time (remember, JavaScript is single-threaded).
In JavaScript’s runtime, we have queues, which hold lists of tasks to be processed. Tasks in these queues wait until the call stack is empty.
Task Queue (or Callback Queue): This queue stores tasks like setTimeout() and setInterval() calls. Tasks here are processed after the call stack is empty and after all tasks in the Microtask Queue have been processed. See more examples of tasks that are stored in this queue on MDN.
Microtask Queue: This queue has priority over the Task Queue. It includes microtasks such as Promise callbacks and asynchronous functions like process.nextTick() and async functions.
The Task Queue works on a FIFO (First-In-First-Out) basis, meaning tasks are processed in the order they’re added, but only after the Microtask Queue is empty.
The event loop is a mechanism that manages the execution of asynchronous code. It observes the call stack and coordinates between the call stack and the queues (Task Queue and Microtask Queue) to keep the code running smoothly.
Let's go through the event loop process step by step. Refer to the image below for a visual representation.
In this example:
By following this order—Call Stack, then Microtask Queue, and finally Task Queue—the event loop helps JavaScript handle asynchronous code efficiently, even within its single-threaded environment.
Now that we understand how the event loop works and how tasks are prioritized, let’s look at some examples.
const a = new Promise(function showA(resolve){ console.log('A'); resolve('B'); }); setTimeout(function showC() { console.log('C'); }, 0); a.then(function showB(b) { console.log(b); }); const d = function showD() { console.log('D'); }; d();
Before continuing, try to think about the order of the output.
✨What do you expect it to be?✨
Let’s break down each part of the code to understand why we get this output.
1. Creating the Promise
const a = new Promise(function showA(resolve) { console.log('A'); resolve('B'); });
2. setTimeout Call
setTimeout(function showC() { console.log('C'); }, 0);
3. a.then Callback
const a = new Promise(function showA(resolve){ console.log('A'); resolve('B'); }); setTimeout(function showC() { console.log('C'); }, 0); a.then(function showB(b) { console.log(b); }); const d = function showD() { console.log('D'); }; d();
4. Defining d
const a = new Promise(function showA(resolve) { console.log('A'); resolve('B'); });
5. Calling d()
setTimeout(function showC() { console.log('C'); }, 0);
Final Output Order:
a.then(function showB(b) { console.log(b); });
GIF for reference
Interactive Example
const d = function showD() { console.log('D'); };
Again, take a moment to think about the order of the output.
✨What do you expect it to be?✨
Let's go with the explanation...
1. Logging "Start!"
d();
A D B C
3. Promise Resolution
console.log("Start!"); setTimeout(function showTimeout() { console.log("Timeout!"); }, 0); Promise.resolve("Promise!") .then(function showPromise(res) { console.log(res); }); console.log("End!");
4. Logging "End!"
console.log("Start!");
Final Output Order:
setTimeout(function showTimeout() { console.log("Timeout!"); }, 0);
GIF for reference
Interactive Example
This chapter wasn’t too long, but I hope these examples helped you understand how the event loop works.
I strongly recommend experimenting with the interactive page to analyze other examples. Playing around on that page can make it much easier to understand the event loop in action.
Thank you so much for all the love on my previous posts!
See you next week! ?
Bye Bye
The above is the detailed content of Technical Interview Questions - Part Event Loop. For more information, please follow other related articles on the PHP Chinese website!