EventLoop

JavaScript is a single-threaded language

JavaScript is a single-threaded programming language. That means you can only do one thing at a time.

Single-threaded execution of task queues: If the previous task is very time-consuming, subsequent tasks have to wait forever, resulting in the problem of program suspension

2. Synchronous and asynchronous tasks

To prevent the problem of a time-consuming task causing the program to freeze, JavaScript divides the tasks to be executed into two categories:

(1) Synchronous task

  • Also known as non-time consuming tasks, these are tasks that are queued for execution on the main thread

  • You can perform the next task only after the previous task is completed

(2) Asynchronous task

  • Also known as time-consuming tasks, asynchronous tasks are delegated by JavaScript to the host environment for execution

  • When the asynchronous task completes, the JavaScript main thread is notified to execute the callback function for the asynchronous task

3. Basic concepts of EventLoop

The JavaScript main thread reads callback functions for asynchronous tasks from the “task queue” and executes them in sequence on the execution stack. This is also called an EventLoop because it is a continuous loop.

Macro and micro tasks

1. What are macro tasks and micro tasks

JavaScript further divides asynchronous tasks into two categories:

(1) Macrotask

  • Asynchronous Ajax requests,

  • SetTimeout and setInterval,

  • File operations

  • Other macro tasks

(2) Microtasks

  • Promise.then,.catch, and.finally

  • process.nextTick

  • Other microtasks