Menu
CoddyTech

The Event Loop

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 18 of 24.

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, even setTimeout(fn, 0), each when its time is up.

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
  • order.js prints 1 sync, 2 microtask, 3 timeout, 4 timeout later, in that order.
  • Keep the four lines where they are. Wrap them in one queueMicrotask and two setTimeout calls.

Run node order.js and compare it with your guess. Then give both timers a delay of 0 and run it again.

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