Loading...
Loading...
Event Loop is a mechanism in JavaScript that manages asynchronous tasks and event queues. It allows JavaScript to work in a single-threaded model, processing asynchronous operations without blocking the main execution thread.
Event Loop is an infinite loop that executes event handlers. During its operation, the browser distributes tasks into two main queues:
queueMicrotask(), MutationObserver.setTimeout, events, timers, fetch requests.setTimeout wait until all synchronous tasks and microtasks are completed.Call Stack (LIFO — Last In, First Out):
Web API:
setTimeout, event handlers, fetch requests go to Web API.Callback Queue (FIFO — First In, First Out):
Macrotasks:
setTimeout, events (onClick, onChange), fetch requests.Microtasks:
queueMicrotask(), MutationObserver.console.log("First message");
setTimeout(() => {
console.log("Second message");
}, 0);
Promise.resolve().then(() => console.log("Third message"));
console.log("Fourth message");
What Happens:
setTimeout places its task in macrotask queue, but won't execute until all microtasks are processed.Promise.resolve().then(...) places task in microtask queue and will execute before next macrotask.Important Note:
Microtasks have priority over macrotasks. So even if you use setTimeout with delay 0, function will execute after all microtasks.