Tell us about the Event Loop in JavaScript.
sobes.tech AI
Answer from AI
The Event Loop in JavaScript is a mechanism that allows asynchronous code to run despite the language's single-threaded nature. It manages the event and callback queues, ensuring non-blocking execution.
When code runs, synchronous operations execute immediately, while asynchronous ones (like setTimeout, promises, events) are placed in the respective queues (callback queue, microtask queue). The Event Loop constantly checks the call stack — if it's empty, it takes tasks from the queues and executes them.
A key feature is that microtasks (such as promise handlers) have priority and are executed immediately after the current stack, before the Event Loop proceeds to the next task from the callback queue.
Example:
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');
The output will be:
Start
End
Promise
Timeout
This is because promises go into the microtask queue and are executed before tasks from setTimeout.