Middle
What is the Event Loop in JavaScript? In what order are tasks executed?
sobes.tech AI
Answer from AI
The Event Loop in JavaScript is a mechanism that allows asynchronous code to execute without blocking the main thread. It operates in a single-threaded environment, managing a task queue and a call stack.
The order of task execution is as follows:
- All synchronous code is executed first, which goes onto the call stack.
- After the stack is cleared, the Event Loop checks the microtask queue, which includes promises (Promise.then/catch/finally) and MutationObserver. All microtasks are executed before moving to the next phase.
- Then, the Event Loop processes the macro task queue, which includes tasks like setTimeout, setInterval, and I/O events.
Thus, the order is: synchronous code → microtasks → macrotasks → repeat the cycle.
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
Because microtasks (promises) are executed before macrotasks (setTimeout).