Questions
What is the event loop and how does it work in JavaScript?
The Scenario
You are a frontend engineer at a social media company. You are building a new feature that needs to make an API call to get some data and then update the UI with the data.
You need to understand how the event loop works so that you can write asynchronous code that is both performant and correct.
The Challenge
Explain what the event loop is in JavaScript and how it works. What is the role of the call stack, the message queue, and the microtask queue?
A junior engineer might have a vague understanding of the event loop. They might not be able to explain the difference between the message queue and the microtask queue, or the implications of this difference.
A senior engineer would be able to provide a detailed explanation of the event loop and its different components. They would also be able to explain the difference between the message queue and the microtask queue and would have a clear understanding of how this affects the execution of asynchronous code.
Step 1: Understand the Key Components
| Component | Description |
|---|---|
| Call Stack | A LIFO (Last-In, First-Out) data structure that stores the execution context of the code. |
| Message Queue | A FIFO (First-In, First-Out) data structure that stores the messages to be processed by the event loop. |
| Microtask Queue | A queue for microtasks, such as promise callbacks. Microtasks are executed before the next message in the message queue. |
| Event Loop | A process that constantly checks the call stack and the message queue. If the call stack is empty, it takes the first message from the message queue and pushes it onto the call stack. |
Step 2: The Event Loop in Action
Here’s how the event loop works:
- When a function is called, it is pushed onto the call stack.
- When the function returns, it is popped off the call stack.
- When an asynchronous operation is performed, it is offloaded to the browser’s Web API.
- When the asynchronous operation is complete, a message is added to the message queue.
- The event loop takes the first message from the message queue and pushes its callback function onto the call stack.
- The callback function is executed.
Microtasks vs. Macrotasks
The message queue is also known as the macrotask queue. In addition to the macrotask queue, there is also a microtask queue.
- Macrotasks:
setTimeout,setInterval,setImmediate - Microtasks:
process.nextTick,Promise.then,queueMicrotask
Microtasks are always executed before the next macrotask.
Practice Question
You have a `setTimeout` with a delay of 0ms and a `Promise.then`. Which one will be executed first?