Typorithm · hard

Event Loop

event-loopjavascript-coremicrotaskmacrotask
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Event Loop

0%

Async

After the synchronous code finishes, the event loop drains the microtask queue (promise callbacks) completely before running the next macrotask (setTimeout). That is why this snippet prints 1, 4, 3, 2.

JavaScript runs synchronous code first on a single thread. Here console.log(1) and console.log(4) execute top to bottom, printing 1 then 4 before any async callback gets a chance.

Async callbacks land in two queues. Promise .then callbacks go to the microtask queue; setTimeout callbacks go to the macrotask (task) queue.

After the current synchronous run completes, the event loop drains the entire microtask queue before taking one macrotask. So the promise callback (3) runs before the timeout callback (2), giving the order 1, 4, 3, 2.

01

Synchronous code runs first, before any callback.

02

Promise callbacks are microtasks; setTimeout is a macrotask.

03

All microtasks drain before the next macrotask runs.

console.log(1);
setTimeout(() => console.log(2));
Promise.resolve().then(() => console.log(3));
console.log(4);
// prints: 1, 4, 3, 2

Read the implementation

Connect each part of the code to the concept before you type.

1. Sync runs first

Synchronous code runs immediately, so 1 prints first.

console.log(1);

2. Macrotask

setTimeout queues a macrotask; it runs after all microtasks.

setTimeout(() => console.log(2));

3. Microtask

A then callback queues a microtask, which runs before any macrotask.

Promise.resolve().then(() => console.log(3));

4. Still sync

4 is also synchronous, so it prints right after 1, before any queued task.

console.log(4);

5. Resulting order

Sync (1, 4) runs, then the microtask (3), then the macrotask (2).

// prints: 1, 4, 3, 2

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Event Loop: Lesson & Practice · Typorithm | ApplyDjinn