Event loop is the loop that maintains the execution order (handling asynchronous operations without blocking the main thread) of JavaScript code.
Things to know before diving into event loop:
- Call Stack: This is where JavaScript executes our code. It follows a Last In, First Out (LIFO) structure. When a function is called, a new execution context is created and it gets pushed onto the stack. When the function ends, it’s popped off.
- MicroTasks Queue: Special queue dedicated to queueMicroTask methods, Promise handlers, await callbacks and MutationObserver (interface provides the ability to watch for changes being made to the DOM tree).
- MacroTasks Queue: All other callbacks from Web APIs (setTimeout, setInterval, DOM APIs, fetch) enters the macroTasks queue.
What is Event Loop?
It’s an endless loop that waits for tasks and pushes them into call stack for execution. Since JavaScript is single-threaded, it maintains an execution order to handle both synchronous asynchronous operations based on priority.
- Regular JS code: Synchronous code runs first and fills the call stack.
- MicroTasks: Tasks queued in microTasks queue gets executed.
- MacroTasks: Tasks queued in macroTasks queue gets executed.
// Programmatic way of how the event loop processes tasks
while (true) {
// Step 1: Execute tasks in the call stack
while (!callStack.isEmpty()) {
const currentTask = callStack.pop();
currentTask(); // Executes the task
}
// Step 2: Process all microtasks
while (!microTasksQueue.isEmpty()) {
const microTask = microTasksQueue.shift();
callStack.push(microTask); // Push microtask to call stack for execution
}
// Step 3: Process one macrotask if available
if (!macroTasksQueue.isEmpty()) {
const macroTask = macroTasksQueue.shift();
callStack.push(macroTask); // Push macrotask to call stack for execution
}
// Break if there's nothing left to process
if (callStack.isEmpty() && microTasksQueue.isEmpty() && macroTasksQueue.isEmpty()) {
break;
}
}
Let’s go through an example to understand the workflow better
1. setTimeout(() => console.log(1), 2000);
2. Promise.resolve().then(() => {
3. console.log(2);
4. queueMicroTask(() => console.log(3));
5. });
6. Promise.resolve().then(() => {
7. console.log(4);
8. setTimeout(() => console.log(5));
9. });
10. setTimeout(() => console.log(6));
11. console.log(7);
// 7 2 4 3 6 5 1
Let’s assume we have a 2 queues microTasks and macroTasks. When the code starts executing,
-
() => console.log(1)
gets pushed into the macroTasks queue in 2000ms. -
() => { console.log(2); queueMicroTask(() => console.log(3)); })
gets pushed into the microTasks queue. -
() => { console.log(4); setTimeout(() => console.log(5)); })
gets pushed into the microTasks queue. -
() => console.log(6)
gets pushed into the macroTasks queue in 0ms. -
console.log(7)
executes and prints7
in console. - Now the event loop checks the microTasks queue for tasks and takes
() => { console.log(2); queueMicroTask(() => console.log(3)); })
task and prints2
in console and pushes() => console.log(3)
into microTasks queue. - Next, the event loop checks microTasks queue and takes
() => { console.log(4); setTimeout(() => console.log(5)); })
task and prints4
and pushes() => console.log(5)
into macroTasks queue in 0ms. - Again, the event loop checks microTasks queue and takes
() => console.log(3))
task and prints3
in console. - Since the microTasks queue is empty now, the event loop checks the macroTaskQueue and takes
() => console.log(6)
and prints6
in console. - Event loop takes the next task
() => console.log(5)
from the macroTasks after ensuring that there isn’t any tasks in microTasks queue and prints5
in console. - Event loop takes the next task
() => console.log(1)
from the macroTasks and prints1
in console.
Thank you for reading! I hope you found this blog informative and engaging. If you notice any inaccuracies or have any feedback, please don’t hesitate to let me know.
Top comments (0)