Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
JavaScript for Frontend Interviews
  1. 1.Introduction to JavaScript & Setup
  2. 2.Variables and Data Types
  3. 3.Operators and Expressions
  4. 4.Control Flow: Conditionals
  5. 5.Control Flow: Loops
  6. 6.Functions: Basics
  7. 7.Arrays and Objects
  8. 8.Higher-Order Functions & Callbacks
  9. 9.Scope and Closures
  10. 10.`this` Keyword and Context
  11. 11.Asynchronous JavaScript: Callbacks & Promises
  12. 12.ES6+ Features (Part 1)
  13. 13.ES6+ Features (Part 2)
  14. 14.Error Handling & Debugging
  15. 15.Asynchronous JavaScript: Async/Await
  16. 16.Prototypal Inheritance & `new` Keyword
  17. 17.Event Loop, Microtasks & Macrotasks
  18. 18.Working with the DOM
  19. 19.Advanced Array Methods & Data Structures
  20. 20.Frontend Interview Prep & Best Practices
JavaScript for Frontend Interviews
17

JavaScript · Lesson 17 of 20 · 4 min

Event Loop, Microtasks & Macrotasks

This is the most common advanced JS topic. Nail this, and you prove you understand how async JS actually works under the hood.

JavaScript is single-threaded. One call stack, one thing at a time. Yet we handle multiple operations concurrently. The event loop is the mechanism that makes this possible without true parallelism. It’s a scheduler that decides what code to run next.

Your job in an interview is to demonstrate you understand this scheduler's rules, especially its strict priority system.

The Two Queues: VIP vs. General Admission

When an async operation finishes (e.g., a timer fires, a fetch completes), its callback doesn't run immediately. It's placed in one of two queues.

The Macrotask Queue (or "Task Queue") is for general admission.

  • setTimeout, setInterval
  • I/O operations (network requests, file system)
  • UI events (click, scroll)
  • requestAnimationFrame (a special case, but think of it here)

The Microtask Queue is the VIP list. It gets processed first.

  • Promise.then(), .catch(), .finally()
  • await (the code after an await is scheduled as a microtask)
  • queueMicrotask()
  • MutationObserver

The rule is simple and absolute: after the main script finishes and the call stack is empty, the event loop will run all tasks in the microtask queue to completion. Only after the microtask queue is completely empty will it process one task from the macrotask queue.

This cycle repeats forever.

How to Trace Execution Order

The interview question: You'll be given a code snippet with a mix of console.log, setTimeout, and Promise.then. Your job is to trace the execution and state the output. Don't just give the answer; explain the 'why' for each step, referencing the queues.

Let’s trace this common example.

console.log('A. Script start');

setTimeout(() => {
  console.log('F. Macrotask 1 (setTimeout)');
  Promise.resolve().then(() => {
    console.log('G. Microtask inside Macrotask');
  });
}, 0);

setTimeout(() => {
  console.log('H. Macrotask 2 (setTimeout)');
}, 0);

Promise.resolve().then(() => {
  console.log('C. Microtask 1');
  Promise.resolve().then(() => {
    console.log('D. Microtask 2 (nested)');
  });
});

queueMicrotask(() => {
  console.log('E. Microtask 3');
});

console.log('B. Script end');

Here's the play-by-play:

  1. Synchronous Pass: The engine executes the script top to bottom.

    • console.log('A. Script start') runs. Output: A. Script start.
    • setTimeout is a Web API. Its callback F is sent to the macrotask queue.
    • The second setTimeout sends its callback H to the macrotask queue.
    • Promise.resolve().then() sends callback C to the microtask queue.
    • queueMicrotask() sends callback E to the microtask queue.
    • console.log('B. Script end') runs. Output: B. Script end.
  2. Microtask Drain: The main script is done. The call stack is empty. The event loop checks the microtask queue. It is not empty.

    • It pulls C and runs it. Output: C. Microtask 1.
    • Inside C, another Promise.then() is found. Its callback D is added to the end of the microtask queue.
    • The loop continues. It pulls E and runs it. Output: E. Microtask 3.
    • The loop continues. It pulls D and runs it. Output: D. Microtask 2 (nested).
    • The microtask queue is now empty.
  3. Macrotask Turn: The event loop now picks just one task from the macrotask queue.

    • It pulls F and runs it. Output: F. Macrotask 1 (setTimeout).
    • Inside F, a Promise.then() is found. Its callback G is added to the microtask queue.
    • The macrotask F finishes. The call stack is empty.
  4. Microtask Drain (Again): Before starting the next macrotask, the loop must check for microtasks again.

    • It finds G and runs it. Output: G. Microtask inside Macrotask.
    • The microtask queue is empty again.
  5. Next Macrotask: The loop picks the next macrotask.

    • It pulls H and runs it. Output: H. Macrotask 2 (setTimeout).

Final output: A, B, C, E, D, F, G, H.

The trap: Candidates often forget that a new microtask scheduled inside another microtask runs before any macrotasks. They also forget that a microtask scheduled inside a macrotask runs before the next macrotask.

The Diagram That Explains the Cycle

This flow chart shows the decision-making process of the event loop. The key is the "Drain ALL Microtasks" step that happens after any chunk of JS finishes and before the next macrotask is considered.

Why This Blocks Your UI

The priority system has a direct impact on performance. Because the microtask queue is drained completely, you can block everything else.

Consider an infinite microtask loop:

Promise.resolve().then(function loop() {
  // This will run forever
  Promise.resolve().then(loop);
});

This code will completely starve the macrotask queue. No setTimeout will ever run. No user clicks will ever be handled. The page will be frozen.

A more realistic problem is a long-running synchronous operation inside a microtask. If a Promise.then callback performs a heavy calculation that takes 200ms, the browser is completely locked for that duration. It cannot render updates or respond to input, because it's stuck in the "Drain Microtasks" phase.

Use macrotasks (setTimeout(fn, 0)) to yield to the browser, allowing it to render and handle other tasks before your code runs. Use microtasks only for quick, high-priority work that must happen immediately after the current script.

Try it

Take the main code example from the "How to Trace Execution Order" section. Manually write down the state of the microtask and macrotask queues after each line of the initial script runs. Then, trace the execution step-by-step on paper, predicting the output. Finally, run the code in your browser's console to verify your trace. This 15-minute exercise solidifies the entire model.

Next: We'll apply these concepts when we start Working with the DOM, where events and rendering are managed by this same loop.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Prototypal Inheritance & `new` Keyword

Next

Working with the DOM