Skip to content

How Event Loop Works

Source: JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue

Resume

Imagine you have a little robot named NodeJS that helps you with your homework and chores. The robot can only do one thing at a time (single-thread), but it can remember tasks it needs to do later (promises).

Here’s how the robot’s Event Loop works:

1. Task List: The robot has a list where it writes down all the tasks you ask it to do. This list is called the “task queue.”

2. One by One: The robot looks at the first task on the list and starts working on it. It keeps working until that task is done or until it reaches a point where it has to wait for something, like a timer to go off or a file to be read.

3. Waiting Tasks: If the robot has to wait, it doesn’t just sit around doing nothing. It moves on to the next task on the list while it waits.

4. Checking Back: The robot keeps an eye on the things it’s waiting for. When one of them is ready (like the timer goes off or the file is read), it adds a new task to the list to finish up the waiting job.

5. Looping: This process of checking the task list and handling tasks goes on and on in a loop. The robot is always looking for new tasks to do, doing them one by one, and checking back on the waiting tasks.

So, the Event Loop is like the robot’s way of making sure all the tasks get done, even if it has to wait for some things sometimes. It keeps everything running smoothly by always checking its list and doing tasks one at a time.

Example

console.log("script start");

const interval = setInterval(() => {
  console.log("setInterval");
}, 0);

setTimeout(() => {
  console.log("setTimeout 1");
  Promise.resolve()
    .then(() => console.log("promise 3"))
    .then(() => console.log("promise 4"))
    .then(() => {
      setTimeout(() => {
        console.log("setTimeout 2");
        Promise.resolve()
          .then(() => console.log("promise 5"))
          .then(() => console.log("promise 6"))
          .then(() => clearInterval(interval));
      }, 0);
    });
}, 0);

Promise.resolve()
  .then(() => console.log("promise 1"))
  .then(() => console.log("promise 2"));

// OUTPUTS
// script start
// promise 1
// promise 2
// setInterval
// setTimeout 1
// promise 3
// promise 4
// setInterval
// setTimeout 2
// promise 5
// promise 6