Menu
CoddyTech

The Event Loop

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 26 of 33.

Callbacks and promises run later, and bugs hide in not knowing exactly when.

Node first runs all the synchronous code to the end. Then it runs microtasks: promise callbacks and functions passed to queueMicrotask. Only then come timers. setTimeout(fn, ms) runs fn once, after ms milliseconds. Even setTimeout(fn, 0) waits until the microtasks are done.

setTimeout(() => console.log('C timer'), 0);
Promise.resolve().then(() => console.log('B promise'));
console.log('A sync');
// A sync, B promise, C timer

A delay of 0 means as soon as possible after the microtasks, never before them. Timers fire in order of their delay; with equal delays, the timer set first goes first.

challenge icon

Challenge

Easy

Node runs your code in a fixed order. First the normal lines, then microtasks such as promise callbacks, then timers. Use that order to make four lines print in number order without moving them.

order.js prints its four lines from 4 down to 1. Do not move or reorder the lines. Instead, wrap three of them so they run later.

  1. Leave console.log('1 sync') as it is. Normal code runs first.
  2. Wrap the 2 microtask line in queueMicrotask, so it runs right after the normal code.
  3. Wrap the 3 timeout line and the 4 timeout later line each in its own setTimeout. setTimeout(fn, ms) runs the function fn once, ms milliseconds later. Line 4 is set before line 3, so it needs the longer delay.

node order.js then prints:

1 sync
2 microtask
3 timeout
4 timeout later

Try it: before you run it, guess the order. Then press Run; the terminal shows $ node order.js. Next, give both timers a delay of 0 and run again: 4 timeout later now prints before 3 timeout, because when delays are equal, the timer set first runs first. Put the longer delay back on line 4 before you press Check.

Try it yourself

// Make these lines print in number order without moving them.
// Wrap them in queueMicrotask and setTimeout instead.
console.log('4 timeout later');
console.log('3 timeout');
console.log('2 microtask');
console.log('1 sync');
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Node.js Basics

Practice on your own: Express playground