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 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
Easyorder.jsprints1 sync,2 microtask,3 timeout,4 timeout later, in that order.- Keep the four lines where they are. Wrap them in one
queueMicrotaskand twosetTimeoutcalls.
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');
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeCommand-Line ArgumentsCommands