The Event Loop in JavaScript is a crucial part of how asynchronous operations are
handled. Since JavaScript is single-threaded, the event loop allows non-blocking
execution by managing multiple tasks efficiently.
How Event Loop Works
Call Stack (Execution Context Stack)
JavaScript uses a stack to keep track of function calls.
When a function is called, it gets pushed onto the call stack.
When the function completes, it is popped off the stack.
Web APIs
When asynchronous operations like setTimeout(), fetch(), or event listeners are
called, they are sent to Web APIs (provided by the browser or Node.js).
Callback Queue / Task Queue
Once an async task is completed (e.g., an API response is received), its callback
function is placed in the callback queue.
Microtask Queue (Higher Priority than Callback Queue)
Microtasks include:
Promises (.then, .catch, .finally)
MutationObserver
queueMicrotask()
Microtasks always execute before callbacks from the callback queue.
Event Loop Execution
The Event Loop constantly checks the Call Stack.
If the stack is empty, it pushes the next callback from the Microtask Queue first.
If the Microtask Queue is also empty, it processes the next task from the Callback
Queue.