Skip to content

JavaScript Event Loop ​

JavaScript has a single-threaded execution in the browser. The asynchronous tasks are often offloaded to the browser.

https://youtu.be/eiC58R16hb8?si=ldMmgd575Vuc0NtA This is a good video about JS Event Loop.

Pasted image 20240824113934.png

Call Stack: The call stack is where functions are executed in a Last In, First Out (LIFO) order. When a function is called, it’s pushed onto the stack, and when it finishes, it’s popped off the stack.

Task Queue (or Macro Task Queue): The task queue holds tasks like setTimeout, setInterval, event handlers (like click, load), and setImmediate. When the event loop finds the call stack empty, it picks the first task from the task queue and pushes it onto the call stack for execution.

Microtask Queue: The microtask queue is prioritized over the task queue and holds tasks like Promise callbacks (then, catch, finally), MutationObserver callbacks, and queueMicrotask. Microtasks are executed immediately after the currently executing script and before any tasks in the task queue.

Execution ​

  • The JavaScript engine starts executing the code from the call stack.
  • If a synchronous function is encountered, it’s executed right away.
  • If an asynchronous function (e.g., setTimeout) is encountered, it’s passed to the Web API, which handles it in the background.
  • Once a Web API finishes its task (e.g., a timer completes), it places the associated callback in the task queue
  • When call stack is empty, the microtask queue is checked for new tasks. If it exists, the microtask is executed.
  • When both call stack and microtask queue are empty, the task queue is checked. The first task is executed. After execution, the microtask queue is again checked, giving microtasks a higher priority than the tasks queue.