Sub topic 2
How the Event Loop Schedules Callbacks
This chapter assumes you can write functions and arrow functions, know how let, const, and var are scoped, and can run scripts in Node.js.
The Call Stack, Task Queue, and Microtask Queue
JavaScript runs one piece of code at a time on the call stack. Asynchronous callbacks wait in a queue until the stack is empty. Promise reactions go to the microtask queue, and that queue is fully drained before the next task starts. Timer callbacks go to the task queue.
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('microtask'));
console.log('sync');
// Output: sync, microtask, timeoutA delay of 0 does not mean "now". It means "after the current code and all pending microtasks finish".
Closures and the Loop Variable Trap
A callback closes over variables, not over their values. With var, every callback shares one i, and by the time the callbacks run the loop has already set it to 3. With let, each iteration gets its own binding.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var', i), 0);
}
// var 3, var 3, var 3
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log('let', j), 0);
}
// let 0, let 1, let 2Keeping `this` Intact
When you pass counter.increment as a bare reference, the method is cut off from its object, so this is undefined when it runs. You can fix this with bind or by wrapping the call in an arrow function.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counter = new Counter();
[1, 2].forEach(counter.increment.bind(counter));
[1, 2].forEach(() => counter.increment());
console.log(counter.count); // 4Error-First Callbacks in Node.js
Node.js core APIs pass an error as the callback's first argument, or null if the call succeeded. Check that argument first, and return early when it is set.
const fs = require('node:fs');
fs.readFile('config.json', 'utf8', (err, data) => {
if (err) {
console.error('Read failed:', err.message);
return;
}
console.log('Read', data.length, 'characters');
});Exercise
What does this print, and in what order? setTimeout(() => console.log(1), 0); Promise.resolve().then(() => console.log(2)); console.log(3);
Show answer
3, 2, 1. The synchronous log runs first. Then the Promise microtask runs. The timer task runs last.
Exercise
Why does [1, 2].forEach(counter.increment) throw a TypeError?
Show answer
The method is passed without its object, so this is undefined inside increment. Use counter.increment.bind(counter) or () => counter.increment() instead.