Node.js Timers and Callbacks
Node never waits around: slow tasks run in the background and call you back later. setTimeout runs once, setInterval repeats, and setImmediate runs after the current work.
ExampleNode.js
console.log("1 start");
setTimeout(() => console.log("5 timeout after 10 ms"), 10);
setImmediate(() => console.log("4 immediate"));
process.nextTick(() => console.log("3 nextTick"));
Promise.resolve().then(() => console.log("3b promise"));
console.log("2 end of script");
let n = 0;
const id = setInterval(() => {
n++;
console.log("tick", n);
if (n === 2) clearInterval(id);
}, 20);Output
1 start 2 end of script 3 nextTick 3b promise 4 immediate 5 timeout after 10 ms tick 1 tick 2
The order shows the event loop at work: the script finishes first, then nextTick and promise callbacks, then setImmediate, then timers when their time is up. (A setTimeout of 0 ms and setImmediate can run in either order, so never rely on that.)
Quick check
In what order do things happen: script end or setTimeout callback?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.