LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

Event Loop in JavaScript – Call Stack, Microtasks and Macrotasks

JavaScript Event Loop it controls how JavaScript runs tasks, handles waiting operations and keeps the program responsive. We will understand three important parts: the Call Stack, Microtask Queue and Macrotask Queue.

Event Loop in JavaScript – Call Stack, Microtasks and Macrotasks

TL;DR: The JavaScript event loop manages when code runs. The call stack runs synchronous code first. After the stack becomes empty, microtasks run before the next macrotask. This is how JavaScript handles asynchronous work without blocking the main thread.

1. Why Do We Need the JavaScript Event Loop?

Imagine a UPI payment app handling 10,000 payment requests. Each payment needs validation, a server response, and a status update.

Some operations finish immediately. Others wait for a network response or timer. Should JavaScript stop everything while one operation waits?

No. JavaScript uses the event loop to coordinate these operations.

Event loop = the mechanism that decides which waiting callback runs next.

The problem: Running every operation in one sequence

Consider a payment screen that processes three payments. Each operation runs one after another.

Example 1: Synchronous payment processing without asynchronous handling
function processPayment(paymentId) {
  console.log("Processing payment " + paymentId);
}

processPayment(101);
processPayment(102);
processPayment(103);

console.log("Payment screen ready");
Expected output
Processing payment 101
Processing payment 102
Processing payment 103
Payment screen ready

This works, but real payment operations involve waiting. Network requests do not finish immediately. Timers also need time to expire.

What goes wrong with long-running work?

  1. The user interface can become unresponsive.
  2. Other clicks may wait behind long-running code.
  3. Network responses cannot be handled until JavaScript gets control.
  4. Timers cannot run while the main thread is busy.

Now think about thousands of payment updates arriving close together. We need a clear way to schedule their callbacks.

The solution: Let JavaScript schedule asynchronous work

JavaScript runs synchronous code first. It can then process callbacks when their work becomes ready.

Example 2: Payment updates using a timer and a Promise
console.log("Payment screen opened");

setTimeout(() => {
  console.log("Payment receipt received");
}, 0);

Promise.resolve().then(() => {
  console.log("Payment status updated");
});

console.log("Payment request submitted");
Expected output
Payment screen opened
Payment request submitted
Payment status updated
Payment receipt received

Notice the order. The timer uses zero milliseconds, but it does not run immediately. The Promise callback runs first.

Without the event loop vs with the event loop

How JavaScript handles payment operations
Without asynchronous scheduling With the event loop
Work runs in one blocking sequence. Callbacks wait until JavaScript can run them.
Waiting can block useful work. Timers and network operations can complete outside the call stack.
There is no callback priority model. Microtasks run before the next task.
Long tasks can freeze the interface. Short tasks allow the browser to process other work.

The terms to remember

  • Call stack = the place where JavaScript runs current function calls.
  • Web API = browser features that handle work like timers and network requests.
  • Callback = a function passed to run later.
  • Task queue = a waiting area for tasks ready to run.
  • Microtask = a high-priority queued job, often created by a Promise.
  • Macrotask = a common name for a task such as a timer callback.
  • Event loop = the process that coordinates the stack and waiting work.

2. Understand the Call Stack

The call stack tracks which JavaScript function is running. It follows the Last In, First Out rule.

Last In, First Out means the latest function call finishes first.

Think about a payment function calling a validation function. Validation must finish before payment processing continues.

Example 3: Function calls inside a payment workflow
function validatePayment() {
  console.log("Payment validated");
}

function submitPayment() {
  console.log("Payment submission started");
  validatePayment();
  console.log("Payment submitted");
}

submitPayment();
Expected output
Payment submission started
Payment validated
Payment submitted

How the call stack changes

Animation 1 – Payment function call stack

Step 1 · Start

Global codeCalls submitPayment()
Call stackGlobal execution
→

Step 2 · Nested call

submitPayment()Calls validatePayment()
validatePayment()Runs on top of the stack
→

Step 3 · Return

validatePayment()Finishes and leaves the stack
submitPayment()Continues and then finishes

The stages highlight how nested payment functions enter and leave the call stack.

Each function call adds a new stack frame. A finished function is removed from the stack.

Important: JavaScript cannot run another function on the same main thread while the current synchronous code is still running.

3. What Is the JavaScript Event Loop?

The event loop checks whether JavaScript can process more queued work. It does not run callbacks while the call stack is busy.

In a browser, the event loop works with browser-managed features and task queues. The browser handles timers and network activity outside the JavaScript call stack.

When a callback becomes ready, it waits for its turn. The event loop helps schedule that callback.

Animation 2 – Complete JavaScript event loop workflow

JavaScript execution

Call StackRuns synchronous code
Browser APIsTimers and network work
→

Waiting work

Microtask QueuePromise callbacks
Task QueueTimer and event callbacks
→

Scheduling

Event LoopChecks execution readiness
Next callbackRuns when the stack is clear

The animation highlights the stack, browser work, queues, and callback scheduling stages.

This diagram shows the main idea. The exact browser scheduling model has more detail, including rendering and task sources.

4. What Are Microtasks in JavaScript?

A microtask is a queued job that runs after the current JavaScript task finishes. It runs before the browser takes the next task from the task queue.

Promise callbacks use the microtask queue. The queueMicrotask() function also schedules a microtask.

Common sources of microtasks

  • Promise.then() callbacks.
  • Promise.catch() callbacks.
  • Promise.finally() callbacks.
  • queueMicrotask() callbacks.
  • Mutation observer callbacks in browsers.
Example 4: Promise callbacks run as microtasks
console.log("Payment started");

Promise.resolve().then(() => {
  console.log("Payment validation completed");
});

console.log("Waiting for payment confirmation");
Expected output
Payment started
Waiting for payment confirmation
Payment validation completed

The first two messages run synchronously. The Promise callback waits in the microtask queue.

How microtasks are processed

Animation 3 – Microtask checkpoint

1. Current taskFinish synchronous code
→
2. Stack emptyNo active function calls
→
3. MicrotasksRun queued Promise jobs
→
4. Next taskContinue event loop work

This animation shows the microtask checkpoint before the next task is selected.

JavaScript keeps processing microtasks until the queue becomes empty. New microtasks can join while existing ones run.

Watch out: A microtask that keeps adding more microtasks can delay timers and rendering. This is sometimes called microtask starvation.

5. What Are Macrotasks in JavaScript?

Macrotask is a common teaching term for a task in the event loop. The HTML standard usually calls these simply tasks.

Examples include timer callbacks, user input events, and some message events.

Common task sources

  • setTimeout() callbacks.
  • setInterval() callbacks.
  • Click and keyboard event handlers.
  • Message events, such as those from postMessage().
  • Some browser-managed event callbacks.
Example 5: Timer callback waits for its task
console.log("UPI request created");

setTimeout(() => {
  console.log("Receipt notification displayed");
}, 0);

console.log("Request sent to server");
Expected output
UPI request created
Request sent to server
Receipt notification displayed

The timer does not interrupt the current code. Its callback becomes eligible after its delay.

Remember: Zero milliseconds does not mean immediate execution. It means the timer has no requested delay beyond the browser's scheduling rules.

6. Microtasks vs Macrotasks: What Is the Difference?

Microtasks and tasks compared
Point Microtasks Macrotasks / tasks
Typical source Promise callbacks Timers and user events
Queue processing At a microtask checkpoint Selected by the event loop
Priority in a browser cycle Processed before the next task Runs after the microtask checkpoint
Examples then(), queueMicrotask() setTimeout(), click events
Possible issue Can delay tasks if continually replenished Can be delayed by long-running code

7. Understand the Execution Order with One Example

Now combine synchronous code, a Promise, and a timer. Predict the output before reading it.

Example 6: Synchronous code, microtask, and macrotask
console.log("1. Payment screen opened");

setTimeout(() => {
  console.log("4. Receipt notification");
}, 0);

Promise.resolve().then(() => {
  console.log("3. Payment status updated");
});

console.log("2. Payment request submitted");
Expected output
1. Payment screen opened
2. Payment request submitted
3. Payment status updated
4. Receipt notification

Why does this output appear?

  1. The first log runs immediately.
  2. The timer callback is registered with the browser.
  3. The Promise callback is added to the microtask queue.
  4. The final synchronous log runs.
  5. The call stack becomes empty.
  6. The Promise callback runs at the microtask checkpoint.
  7. The timer callback runs as a later task.

The key rule is simple. Synchronous code runs first, then microtasks, then the next task.

8. A Deeper Example: Microtasks Created by Microtasks

A Promise callback can schedule another microtask. JavaScript processes that new microtask before moving to the next task.

Example 7: Nested microtask scheduling
console.log("Payment started");

setTimeout(() => {
  console.log("Timer callback");
}, 0);

Promise.resolve().then(() => {
  console.log("First microtask");

  queueMicrotask(() => {
    console.log("Second microtask");
  });
});

console.log("Payment request sent");
Expected output
Payment started
Payment request sent
First microtask
Second microtask
Timer callback

The second microtask joins the queue while the first one runs. It still runs before the timer task.

9. What Happens When JavaScript Uses async and await?

async makes a function return a Promise. await pauses that function until its Promise settles.

It does not block the entire JavaScript thread. The rest of the program can continue.

Example 8: Payment confirmation with async and await
async function confirmPayment() {
  console.log("Checking payment");

  await Promise.resolve();

  console.log("Payment confirmed");
}

console.log("Screen loaded");

confirmPayment();

console.log("User can continue");
Expected output
Screen loaded
Checking payment
User can continue
Payment confirmed

The function runs until it reaches await. Its remaining work continues later as a Promise job.

What does await really do?

  • The function starts running normally.
  • The expression after await is evaluated.
  • The function pauses at that point.
  • The remaining function code is scheduled to continue later.
  • Other JavaScript work can run in the meantime.
Important: Even an already resolved Promise causes the code after await to continue asynchronously.

10. Does the Event Loop Work the Same in Node.js?

The event loop exists in both browsers and Node.js. However, their scheduling details are not identical.

Browsers follow the HTML event loop model. Node.js uses the event loop provided by its runtime, built around libuv.

Node.js has phases for timers, pending callbacks, poll, check, and close callbacks. It also has a special process.nextTick() queue.

Browser and Node.js event loop differences
Area Browser Node.js
Runtime Browser environment Node.js runtime
Timers setTimeout() and setInterval() Timer phase scheduling
Promise callbacks Microtask queue Microtask queue
Extra scheduling Browser task sources and rendering process.nextTick() and event loop phases
Rendering Browser manages page rendering No browser page rendering loop
Interview warning: Do not apply every browser ordering example directly to Node.js. Node.js has additional scheduling rules.

11. Common Event Loop Mistakes

1. Thinking setTimeout runs immediately

setTimeout(callback, 0) schedules a callback. It does not interrupt the current code.

2. Thinking every asynchronous callback is a microtask

Promise callbacks are microtasks. Timer callbacks are tasks.

3. Thinking await blocks JavaScript

await pauses the current async function. It does not block the entire thread.

4. Ignoring long synchronous operations

A long loop blocks the main thread. The browser cannot process other JavaScript tasks during that time.

5. Creating endless microtasks

Continuously adding microtasks can delay timers and page rendering. Keep microtask work short.

6. Assuming all runtimes use identical rules

Browser and Node.js scheduling details differ. Always check the runtime when exact ordering matters.

12. Best Practices for JavaScript Developers

  • Keep synchronous functions short and focused.
  • Use Promises for asynchronous operations.
  • Use async and await for readable asynchronous code.
  • Avoid long loops on the browser's main thread.
  • Use Web Workers for suitable CPU-heavy browser work.
  • Do not use microtasks as a replacement for every timer.
  • Handle Promise rejections with suitable error handling.
  • Test scheduling behavior in the actual runtime you deploy.

13. JavaScript Event Loop Interview Questions

Q1. What is the event loop in JavaScript?

Answer: The event loop coordinates the call stack and queued work. It helps JavaScript run asynchronous callbacks when the stack is ready.

Q2. What is the call stack?

Answer: The call stack tracks active function calls. JavaScript runs the function at the top of the stack.

Q3. What is a microtask?

Answer: A microtask is a queued job processed at a microtask checkpoint. Promise callbacks are common examples.

Q4. What is a macrotask?

Answer: Macrotask is a common name for an event loop task. Timer callbacks and user events are examples.

Q5. Which runs first: Promise or setTimeout?

Answer: In the usual browser example, the Promise callback runs first. It is a microtask, while the timer callback is a task.

Q6. Does setTimeout with zero milliseconds run immediately?

Answer: No. It makes the callback eligible after the requested delay. The callback still waits for its task turn.

Q7. Does await block the main thread?

Answer: No. It pauses the current async function. Other JavaScript work can continue.

Q8. Can microtasks delay timers?

Answer: Yes. The runtime processes queued microtasks before selecting the next task. A continuously growing microtask queue can cause delays.

Q9. Is the browser event loop the same as Node.js?

Answer: No. Both coordinate asynchronous work, but their scheduling models differ. Node.js has event loop phases and a next-tick queue.

Q10. What happens when the call stack is busy?

Answer: Queued callbacks wait. JavaScript cannot run another callback on the same thread until the current stack work finishes.

14. Hands-On Practice

Use these exercises to test your understanding. Predict each output before running the code.

Exercise 1: Predict the execution order

Use the UPI payment example. Which message appears first?

console.log("A");

setTimeout(() => console.log("B"), 0);

Promise.resolve().then(() => console.log("C"));

console.log("D");

Expected answer: A, D, C, B.

Exercise 2: Add another microtask

Use queueMicrotask() inside a Promise callback. Check whether it runs before the timer.

Exercise 3: Use async and await

Create an async payment confirmation function. Add one log before and one after await. Predict the output.

Exercise 4: Try a different real-life example

Build a railway ticket booking example. Log the booking request, a Promise confirmation, and a timer-based ticket notification. Explain the output order.

15. Final Summary

  • The call stack runs synchronous JavaScript code.
  • Browser APIs handle features such as timers and network requests.
  • Promise callbacks are placed in the microtask queue.
  • Timer callbacks are scheduled as tasks.
  • Microtasks run at a checkpoint before the next task.
  • The event loop coordinates when queued work can run.
  • Long synchronous work can block the main thread.
  • Browser and Node.js scheduling details are different.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.