JavaScript is a programming language with a single-threaded nature, but it can handle asynchronous operations. This is possible thanks to the Event Loop — a mechanism that allows JavaScript to execute code without blocking the main thread. In this post, we will explore how the Event Loop works, why it is important, and how to properly use its features.
Basics of the Event Loop
The Event Loop is based on three main components:
- Call Stack — the place where synchronous functions are executed.
- Task Queue — a list of callbacks waiting to be executed.
- Microtask Queue — a queue for Promises and other microtasks.
Let's consider an example:
console.log("Start");
setTimeout(() => {
console.log("setTimeout");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
The expected order of execution:
-
console.log("Start")— is output immediately. -
setTimeoutdefers the execution of the callback to the Task Queue. -
Promise.resolve().then(...)adds the callback to the Microtask Queue. -
console.log("End")— is output immediately. - After the synchronous code finishes, the Event Loop checks the Microtask Queue —
console.log("Promise")is executed. - Only after that is the callback from the Task Queue executed —
console.log("setTimeout").
The result in the console will be:
Start
End
Promise
setTimeout
Why setTimeout(..., 0) does not execute immediately?
setTimeout(..., 0) does not mean that the function will execute immediately. It adds the callback to the Task Queue, which is processed only after all microtasks have been executed.
An example where this is clearly visible:
setTimeout(() => console.log("setTimeout"), 0);
for (let i = 0; i < 1e9; i++) {} // Blocking the main thread
console.log("End of loop");
Here, setTimeout is delayed until the loop finishes, even though it is set to 0 milliseconds.
Using queueMicrotask
If you need to execute code earlier than setTimeout, you can use queueMicrotask:
queueMicrotask(() => console.log("Microtask"));
console.log("Main code");
The result:
Main code
Microtask