JavaScript The Event Loop

person shubham sharmafolder_openJAVASCRIPT, Node jslocal_offer, access_time March 26, 2022
  • JavaScript is single threaded. so it needs event loop to run asynchronous (Multi Thread) code.
  • JavaScript first runs synchronous code, then it queue asynchronous code to call later.
  • Asynchronous code is called/executed by event loop.
  • System/Browser takes synchronous code and put them as tasks. then these tasks are put them into queue.
  • The Event Loop has one simple job — to monitor the is there any task to handle.
  • System/Browser push the task to call stack.
  • Then the event loop will check the call stack and execute the task.
  • Then it waits for the next task to be pushed to the call stack.

Asynchronous tasks are divided into two type of tasks Micro tasks and Macro tasks.
No.Micro tasksMacro tasks
1Micro tasks are tasks that are executed while the event loop is busy.Macro tasks are tasks that are executed after the event loop is idle.
2Micro tasks are used to keep the UI responsive.Macro tasks are used to keep the CPU busy.
3Micro tasks has higher priority than Macro tasks.Macro tasks has lower priority than Micro tasks.
4Micro tasks are executed before Macro tasks.Macro tasks are executed after Micro tasks.
5Micro tasks are executed in the order they are queued.Macro tasks are executed in the order they are queued.

The output will be:

Checkout the cool explanation
warningComments are closed.