Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
09

Frontend System Design · Lesson 9 of 86 · 5 min

Event Loop: Call Stack, Task and Microtask Queues

This is how you nail the "predict the console output" questions that test your core understanding of async JavaScript.

When an interviewer asks you to trace a mix of setTimeout, Promises, and console.log statements, they aren't testing your memory. They're testing your mental model of how JavaScript, a single-threaded language, handles concurrency. Get this right, and you signal a deep understanding of the browser's runtime.

The Single Thread and Its Limits

JavaScript has one call stack. This means it can only do one thing at a time. If you run a function that takes 500ms to complete, nothing else happens for 500ms. The browser can't respond to clicks, it can't rerender the page, it's frozen. This is called "blocking the main thread."

The call stack is a simple LIFO (Last-In, First-Out) queue. When you call a function, it's pushed onto the stack. When it returns, it's popped off. All your synchronous code runs here.

To avoid blocking, the browser gives you Web APIs like setTimeout or fetch. When you call one, the browser offloads the work from the call stack and handles it elsewhere. When the work is done (the timer finishes, the network request completes), the callback function you provided doesn't just jump back into your code. It's placed in a queue, waiting for its turn.

The Two Queues: Task vs. Microtask

There isn't just one queue; there are two, with a strict priority system. This priority is the most common source of confusion and the number one thing interviewers test.

Task Queue (or Macrotask Queue): This is the lower-priority queue. It holds callbacks for events like setTimeout, setInterval, I/O operations, and user interactions (clicks, scrolls).

Microtask Queue: This is the high-priority queue. It holds callbacks for Promises (.then(), .catch(), .finally()), queueMicrotask(), and MutationObserver.

The distinction is critical. Microtasks are for work that needs to happen immediately after the current script finishes, but before the browser does anything else, like rendering or running the next task.

The Rules of Execution

The Event Loop is the orchestrator that decides what code to run next. It has one simple, repeating job.

The trap: Candidates often describe the event loop as "when the call stack is empty, move something from a queue." That's too simple. The real algorithm is what separates a junior from a senior answer.

Here is the precise logic, in order:

  1. Run synchronous code until the call stack is empty.
  2. Check the Microtask Queue. Are there any microtasks?
  3. If yes, pull every single microtask from the queue and execute them one by one until the queue is empty. If new microtasks are added during this process, they are also executed before moving on.
  4. Only when the Microtask Queue is completely empty, check the Task Queue.
  5. If there's a task, pull just one task from the queue and execute it.
  6. After that single task finishes, go back to step 2 and check for microtasks again.

This cycle—run one task, then drain the microtask queue—is the core of it all.

Trace This Code: A Common Interview Problem

You will be given a snippet like this and asked for the output. Don't guess. Trace the execution using the rules above.

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

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

Promise.resolve().then(() => {
  console.log('C. Promise 1 (Microtask)');
  setTimeout(() => {
    console.log('E. setTimeout in Promise (Task)');
  }, 0);
});

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

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

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

Let's trace it step-by-step:

  1. Synchronous Pass:

    • console.log('A. Script start') runs. Output: A. Script start.
    • setTimeout for F is found. Its callback is sent to the Web APIs.
    • Promise.resolve().then() for C is found. Its callback is placed in the Microtask Queue.
    • Promise.resolve().then() for D is found. Its callback is placed in the Microtask Queue.
    • setTimeout for H is found. Its callback is sent to the Web APIs.
    • console.log('B. Script end') runs. Output: B. Script end.
    • The Web API timers for F and H expire immediately and their callbacks are placed in the Task Queue. The order is preserved: F then H.
    • The initial script is done. The call stack is empty.
  2. Event Loop: Microtask Check:

    • The Event Loop sees the Microtask Queue has items (C, then D).
    • It executes C. Output: C. Promise 1 (Microtask).
    • Inside C, a setTimeout for E is found. Its callback is sent to Web APIs, which then places it in the Task Queue after F and H.
    • It executes D. Output: D. Promise 2 (Microtask).
    • The Microtask Queue is now empty.
  3. Event Loop: Task Check:

    • The Event Loop sees the Task Queue has items (F, H, E).
    • It pulls one task: F.
    • It executes F. Output: F. setTimeout 1 (Task).
    • Inside F, Promise.resolve().then() for G is found. Its callback is placed in the Microtask Queue.
    • Task F is finished.
  4. Event Loop: Microtask Check (again):

    • Before checking for the next task, the loop must check for microtasks. It finds G.
    • It executes G. Output: G. Promise in setTimeout (Microtask).
    • The Microtask Queue is now empty.
  5. Event Loop: Task Check:

    • The Event Loop sees the Task Queue has items (H, E).
    • It pulls one task: H.
    • It executes H. Output: H. setTimeout 2 (Task).
    • Task H is finished.
  6. Event Loop: Microtask Check:

    • The Microtask Queue is empty.
  7. Event Loop: Task Check:

    • The Event Loop sees the Task Queue has one item (E).
    • It pulls E.
    • It executes E. Output: E. setTimeout in Promise (Task).
    • Task E is finished.

Final Output:

A. Script start B. Script end C. Promise 1 (Microtask) D. Promise 2 (Microtask) F. setTimeout 1 (Task) G. Promise in setTimeout (Microtask) H. setTimeout 2 (Task) E. setTimeout in Promise (Task)

The key is realizing that microtask G runs before tasks H and E, even though H and E were queued earlier. This is because the microtask queue is checked after every task.

Try it

Take the code example from the last section. Change the first Promise.resolve().then(...) to new Promise(res => setTimeout(res, 0)).then(...). Predict the new output, then run the code in your browser console to verify. Think about why moving the promise resolution into a setTimeout (a task) dramatically changes the execution order.

Next: We'll see how async/await is syntactic sugar over Promises, using this same microtask system to make async code easier to read and write in Async JavaScript: Promises and async/await.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Reflows and Repaints Explained

Next

Async JavaScript: Promises and async/await