The event loop

What is its purpose?

It schedules callbacks to be able to be executed.

Topics involved

  • The call stack: When a function is executed (synchronous code or callbacks), it enters the call stack. The call stack contains all the current executing functions, starting for the root (anonymous).

  • The task queue: Its a queue where asynchronous tasks are queued when they are completed.

  • The microtask queue: It’s a queue where asynchronous microtasks are queued when they are completed.

How event loop works?

The event loop checks continuosly the call stack. If it is empty, it will check if any microtask is in the microtasks queue. If any, it will execute the callback and as soon as executed, it will enter the call stack. Then, it will check the task queue and if there is any task, it will execute the callback and as and as soon as executed, it will enter the call stack. This is a process that happens continuously as the name suggests.

Small diagram

Small example

// Synchronous code
console.log(1);

// Microtask
Promise.resolve().then(() => {
  console.log(2);
});

console.log(3);

// Task
setTimeout(() => {
  console.log(4);
}, 0);

Promise.resolve().then(() => {
  console.log(5);
});

console.log(6);

Example output

1
3
6
2
5
4

0
Subscribe to my newsletter

Read articles from Jon Andoni Castelo Meléndez directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jon Andoni Castelo Meléndez
Jon Andoni Castelo Meléndez

I'm a full-stack and DevOps developer with four years of experience. I usually work with Angular, Nodejs, MongoDB, and Kubernetes