Feb 15, '25 02:00

Events in JavaScript: how the Event Loop works

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 ...

Read post
Share
🔥 More posts
This content has been automatically translated from Ukrainian.

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:

  1. console.log("Start") — is output immediately.
  2. setTimeout defers the execution of the callback to the Task Queue.
  3. Promise.resolve().then(...) adds the callback to the Microtask Queue.
  4. console.log("End") — is output immediately.
  5. After the synchronous code finishes, the Event Loop checks the Microtask Queue — console.log("Promise") is executed.
  6. 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

🔥 More posts

All posts
Feb 17, '25 02:00

What is SASS?

SASS is a preprocessor for CSS that allows you to write styled code faster and more efficiently. SASS ...