What is the event loop in JavaScript runtimes?
Answer:
The event loop is a fundamental mechanism in JavaScript that enables non-blocking, asynchronous programming by managing the execution of multiple tasks, including those initiated by events, timers, or external resources like APIs.
How the Event Loop Works:
- Call Stack:
- A stack where function calls are added when invoked and removed when execution completes.
- Example:
function sayHello() {
console.log('Hello');
}
sayHello(); // Function added to the stack, executed, then removed.
- Web APIs/Background Tasks:
- When asynchronous operations (e.g.,
setTimeout
,fetch
) are initiated, they are sent to the browser or Node.js environment to be handled externally.
- Task Queue/Callback Queue:
- Once an asynchronous task completes, its callback is added to the task queue.
- Microtask Queue:
- Contains tasks from
Promise
callbacks orMutationObserver
. - These are given priority over the regular task queue.
- Event Loop:
- Continuously monitors the call stack and task queues.
- If the call stack is empty, it pushes tasks from the microtask queue first, then from the task queue.
Visual Example:
console.log('Start');
setTimeout(() => {
console.log('Timer finished');
}, 0);
Promise.resolve().then(() => {
console.log('Promise resolved');
});
console.log('End');
Output:
Start
End
Promise resolved
Timer finished
Explanation:
console.log('Start')
andconsole.log('End')
are synchronous and run immediately.- The
Promise
callback (microtask) runs before thesetTimeout
callback (macrotask) because microtasks have higher priority.
Key Points:
- JavaScript is single-threaded but achieves concurrency via the event loop.
- Microtasks (e.g., promises) are handled before macrotasks (e.g., timers).