Sub topic 12
Closures in Callbacks, Timers, and Event Handlers
This chapter assumes you know what a closure is, that closures capture variables rather than values, and how let differs from var in loops. All code runs in Node.js 16 or later, or in a browser console.
A callback is a function you hand to some other code so that code can call it later. When you pass a callback to setTimeout, addEventListener, or a promise's .then, the function you define usually runs after the surrounding function has returned. The callback can still use that function's variables because it is a closure.
Timers Run Later and Read Current Values
A timer callback reads its captured variables when it runs, not when it was scheduled. It sees whatever the variable holds at that moment.
function scheduleGreeting(name) {
let message = `Hello, ${name}`;
setTimeout(() => {
console.log(message);
}, 100);
message = `Goodbye, ${name}`;
}
scheduleGreeting('Ada'); // after 100 ms: "Goodbye, Ada"By the time the callback fires, scheduleGreeting has returned and message has been reassigned. The closure keeps message alive and reads its latest value.
Event Handlers Keep State Between Events
An event handler is a callback that can run many times. A variable it closes over keeps its value between calls, so you can track state without a global variable. This example uses EventTarget, which exists in both browsers and Node.js:
function trackClicks(target) {
let clicks = 0;
target.addEventListener('click', () => {
clicks += 1;
console.log(`Clicked ${clicks} time(s)`);
});
}
const button = new EventTarget();
trackClicks(button);
button.dispatchEvent(new Event('click')); // Clicked 1 time(s)
button.dispatchEvent(new Event('click')); // Clicked 2 time(s)Each call to trackClicks creates its own clicks variable, so two buttons get two separate counters.
Removing Handlers Needs the Same Function
A common mistake is trying to remove a listener by passing a new function that looks the same. removeEventListener matches by reference, so you have to keep a reference to the original closure:
function listenOnce(target, onFire) {
const handler = (event) => {
onFire(event.type);
target.removeEventListener('ping', handler);
};
target.addEventListener('ping', handler);
}
const emitter = new EventTarget();
listenOnce(emitter, (type) => console.log('Got', type));
emitter.dispatchEvent(new Event('ping')); // Got ping
emitter.dispatchEvent(new Event('ping')); // (nothing)The handler can refer to itself because handler is in its own scope.
Promise Callbacks
Promise callbacks work the same way. In the example below, .then runs after loadUser returns and still has access to id:
function loadUser(id) {
const started = Date.now();
return Promise.resolve({ id, name: 'Ada' }).then((user) => {
console.log(`Loaded ${user.name} (id ${id}) in ${Date.now() - started} ms`);
return user;
});
}
loadUser(7);Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| A callback logs a newer value than expected | The variable was reassigned before the callback ran | Copy the value into a `const` before scheduling |
| A listener won't detach | A new function was passed to `removeEventListener` | Store the handler in a variable and pass that same variable |
| Every loop callback logs the same index | `var` shares one binding across iterations | Use `let` in the loop header |
Exercise
What does this code log, and why? function f() { let n = 1; setTimeout(() => console.log(n), 0); n = 5; } f();
Show answer
It logs 5. The arrow function closes over the variable n, not its value at scheduling time. The timer callback runs only after f finishes, and by then n has been set to 5.
Exercise
Write a function makeLimitedHandler(target, max) that logs each 'click' on target and removes its own listener after max clicks.
Show answer
function makeLimitedHandler(target, max) { let count = 0; const handler = () => { count += 1; console.log('click', count); if (count >= max) target.removeEventListener('click', handler); }; target.addEventListener('click', handler); } The closure holds count between events and keeps a reference to handler so it can remove itself.