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 timerA 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
EasyNode 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.
- Leave
console.log('1 sync')as it is. Normal code runs first. - Wrap the
2 microtaskline inqueueMicrotask, so it runs right after the normal code. - Wrap the
3 timeoutline and the4 timeout laterline each in its ownsetTimeout.setTimeout(fn, ms)runs the functionfnonce,msmilliseconds 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 laterTry 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');
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