Understanding the JavaScript Event Loop
Shivam Kumar Singh
Product Engineer | Full-Stack Developer | DSA | 1750+ on LeetCode | Climate Tech & ESG Enthusiast
JavaScript's event loop is fundamental to how asynchronous tasks are handled in a synchronous, single-threaded environment. This summary provides an overview of key concepts related to the event loop.
Call Stack
The call stack manages the execution order of code. It operates as a Last In First Out (LIFO) data structure, handling the sequence of operations.
Global Execution Context
JavaScript code operates within the Global Execution Context, undergoing two phases:
Memory Creation Phase
Code Execution Phase
JavaScript Web APIs
Web browsers provide APIs like setTimeout(), setInterval(), clearTimeout(), clearInterval(), etc., enabling execution of additional tasks that can't run on the main thread.
Callback Queue (Task Queue/Macro Task Queue)
After the browser completes a timer set by Web APIs, callback functions aren't immediately added to the call stack. Instead, they're placed in the callback queue to maintain the correct execution sequence.
Microtask Queue
Similar to the Callback Queue, the Microtask Queue has higher priority. It holds callback functions from Promises and Mutation Observer, executing before the Callback Queue.
Event Loop
Source: "Namaste JavaScript" - Credits to Akshay Saini