Course contentsShow
← JavaScript
Lesson 1214 of 2,72327. The Event LoopFree lesson

Order of Execution in the Loop

Understanding the sequence: run script, drain microtasks, render, then take next task from queue.

Order of Execution in the Loop

You'll learn the precise sequence the event loop follows every single cycle.

The Step-by-Step Dance

The event loop doesn't just randomly pick work to do—it follows a strict choreography every time it completes a cycle:

  1. Run the current script (or task) from the task queue to completion
  2. Drain all microtasks — execute every single microtask in the microtask queue until it's empty
  3. Render — browser updates the screen if needed (not every loop!)
  4. Take the next task — grab one task from the task queue and repeat

Think of it like a restaurant kitchen: First, complete the current order (task). Then, immediately handle all the small corrections called out by waiters (microtasks). Only then do you ring the bell to send food out (render). Finally, you pick up the next order ticket.

Why This Order Matters

This sequence explains why promises always resolve before the next setTimeout, even with zero delay. The promise callback goes into the microtask queue (step 2), which fully empties before any new task from setTimeout (step 4) can run.

setTimeout(() => console.log('Task'), 0);
Promise.resolve().then(() => console.log('Microtask'));
console.log('Script');

// Output:
// Script
// Microtask  
// Task

The synchronous script runs first, microtasks drain next, then the task queue gets attention.

Key Takeaway: Every event loop cycle follows the same order: execute one task, drain all microtasks, render if needed, then pick the next task—this unchanging sequence determines when your asynchronous code actually runs.