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:

  1. Call Stack:
function sayHello() {
  console.log('Hello');
}
sayHello(); // Function added to the stack, executed, then removed.
  1. Web APIs/Background Tasks:
  1. Task Queue/Callback Queue:
  1. Microtask Queue:
  1. Event Loop:

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:

Key Points:

MDN Web Docs: Event Loop