Skip to primary content
Web Technical Tutorial

Understanding the JavaScript Event Loop & Asynchronous Execution

Understand how single-threaded JavaScript handles asynchronous operations: Call Stack, Web APIs, Microtask queue (Promises), and Macrotask queue (setTimeout).

Web
console.log("1: Synchronous start");

setTimeout(() => {
    console.log("4: Macrotask callback (setTimeout)");
}, 0);

Promise.resolve().then(() => {
    console.log("3: Microtask callback (Promise)");
});

console.log("2: Synchronous end");

// Output Order:
// 1: Synchronous start
// 2: Synchronous end
// 3: Microtask callback (Promise)
// 4: Macrotask callback (setTimeout)

1. The Single-Threaded Nature of JavaScript

JavaScript has a single call stack and executes one command at a time. It delegates long-running tasks like timers, network requests, and DOM events to browser Web APIs.

2. Microtasks vs. Macrotasks

When an asynchronous operation finishes, its callback enters one of two queues:

  • Microtask Queue: Holds Promise callbacks (.then, async/await) and MutationObservers.
  • Macrotask (Task) Queue: Holds callbacks from setTimeout, setInterval, and I/O events.

Crucially, the Event Loop drains the entire Microtask queue before moving on to the next Macrotask.

Key Engineering Takeaways
  • Promises always resolve before setTimeout callbacks even with a 0ms delay.
  • Heavy computational loops block the Call Stack and freeze the browser UI.
  • Use Web Workers for heavy CPU-bound processing without degrading UI responsiveness.

Frequently Asked Questions

Why does setTimeout(fn, 0) not run immediately?
Because it is placed in the task queue and must wait until the current call stack and all microtasks have completely drained.
Master This in Our Ghaziabad Coding Labs

Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.

Explore Related Course Call 7503962162
Physical Training Center

Visit Our Ghaziabad Training Center

Join classroom batches, attend interactive lab sessions, code with mentors, and take advantage of our high-speed dev workstations.

Campus Address:
C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad, Ghaziabad, Uttar Pradesh
Direct Counseling Helpline:
Call 7503962162
Get Google Maps Directions Call Now: 7503962162 Explore Ghaziabad Training Hub
Call 7503962162 Get Course Details