Mastering the JavaScript Event Loop requires understanding the boundary between the Microtask Queue (Job Queue) and the Macrotask Queue (Task Queue). Misunderstanding task scheduling leads to subtle race conditions, delayed rendering frames, and interface freezes.
1. The Two Asynchronous Queues
JavaScript categorizes asynchronous callbacks into two distinct queues with vastly different execution priorities:
Because the engine must drain the entire Microtask Queue before rendering or moving to the next macrotask, recursively scheduling microtasks will freeze the browser completely:
1// DANGER: Freezes browser tab completely! UI never repaints!
2functioninfiniteMicrotask(){
3 Promise.resolve().then(infiniteMicrotask);
4}
5// infiniteMicrotask(); // Call stack never yields to UI paint!
4. When to Use queueMicrotask()
The queueMicrotask() standard API allows you to schedule a function to run asynchronously after the current synchronous function finishes, but before browser rendering or timer macrotasks:
1functiontrackTelemetry(event){
2// Enqueue telemetry without blocking current synchronous work,
3// but ensure it executes before the next render frame:
4queueMicrotask(()=>{
5sendBeacon('/analytics', event);
6});
7}
Interactive Quiz• Knowledge Check
Practice Quiz
Question 1
What is the execution priority between the Microtask Queue and the Macrotask Queue?
Question 2
Which of the following schedules a callback in the Microtask Queue?
Question 3
What happens if microtasks recursively enqueue new microtasks indefinitely?
Question 4
How many macrotasks does the Event Loop execute before checking the microtask queue?
Question 5
What standard Web API allows developers to explicitly enqueue a callback into the microtask queue without creating a dummy Promise?
Next Lesson
Custom Promise Implementation
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.