Event Loop
The JavaScript Event Loop is a fundamental concept in understanding how JavaScript handles asynchronous operations. It enables JavaScript to perform non-blocking I/O operations, making it possible to run other code while waiting for operations to complete.
What is the Event Loop?
JavaScript is single-threaded, meaning it can only execute one operation at a time. The Event Loop allows JavaScript to perform asynchronous operations like HTTP requests, file reading, or timers without blocking the main thread.
How It Works
-
Call Stack: The call stack is where JavaScript keeps track of function calls. When a function is called, it gets pushed onto the call stack. When the function execution is complete, it is popped off the stack.
-
Web APIs: Web APIs (such as
setTimeout
,fetch
, etc.) handle asynchronous operations and move the callback functions to the task queue when their operations are complete. -
Task Queue: The task queue (or callback queue) holds the functions that are waiting to be executed. When the call stack is empty, the event loop takes functions from the task queue and pushes them onto the call stack.
-
Microtask Queue: Microtasks, such as
Promise
callbacks andMutationObserver
callbacks, are given higher priority than regular tasks. They are processed before the task queue. -
Event Loop Process:
- The event loop continuously checks if the call stack is empty.
- If the call stack is empty, it looks at the microtask queue and executes all microtasks.
- After processing microtasks, it then processes tasks from the task queue.
- This process repeats, allowing JavaScript to handle multiple asynchronous operations efficiently.
Example
Here’s a simple example to illustrate how the event loop works:
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
Promise.resolve().then(() => {
console.log('Promise');
});
console.log('End');
output
Start
End
Promise
Timeout