Sub topic 12
Closures in Callbacks, Timers, and Event Handlers
This chapter assumes you already know how a closure forms, that closures capture variables rather than values, and how let and var differ inside loops. You should also be able to pass a function as an argument. All examples run in Node.js 16 or later. The event examples use EventTarget, which works the same way in Node and in browsers.
Callbacks are where closures appear most often in everyday JavaScript. When you hand a function to setTimeout, addEventListener, or .then, you are asking the runtime to call it later. "Later" usually means after the function that created the callback has already returned. Even so, the callback still needs the variables it refers to, and the closure is what keeps them available.
Why Deferred Code Depends on Closures
A callback is a function passed to other code that calls it at some point. With synchronous callbacks such as array.map, the outer function is still running when the callback executes. With asynchronous callbacks, the outer function has usually finished. Its local variables would disappear if no closure kept a reference to its lexical environment.
function scheduleGreeting(name, delayMs) {
const greeting = `Hello, ${name}`;
setTimeout(() => {
console.log(greeting);
}, delayMs);
console.log('scheduleGreeting has returned');
}
scheduleGreeting('Ada', 100);
// scheduleGreeting has returned
// Hello, Ada (about 100 ms later)By the time the arrow function runs, scheduleGreeting has returned and its execution context is gone. The arrow function still holds a reference to the environment that contains greeting and name. As long as the timer is pending, that environment stays alive.
Timers Read Values When They Fire
A closure captures a variable, not a copy of its value. With deferred callbacks, the value you see is the one the variable holds when the callback runs. It is not the value from when you scheduled it. This is the source of many timing bugs.
let status = 'pending';
setTimeout(() => {
console.log('status:', status);
}, 0);
status = 'done';
// status: doneA delay of 0 does not mean "run now". It means "run after the current synchronous code finishes and the event loop gets to it". The assignment status = 'done' runs first.
Taking a Snapshot on Purpose
If you need the value as it was at scheduling time, copy it into a binding that never changes. You can also pass it as an argument. setTimeout forwards any extra arguments to the callback.
let status = 'pending';
// Option 1: copy into a const that the callback captures
const statusAtSchedule = status;
setTimeout(() => console.log('copied:', statusAtSchedule), 0);
// Option 2: pass the current value as an argument
setTimeout((s) => console.log('argument:', s), 0, status);
status = 'done';
// copied: pending
// argument: pendingBoth options give the callback its own binding that nothing else reassigns. The closure still captures by reference, but the reference now points at a value that stays fixed.
Event Handlers with Private State
An event handler is a callback the runtime calls each time an event happens. A closure gives each handler state that persists between events without global variables.
function makeClickCounter(target) {
let clicks = 0;
target.addEventListener('click', () => {
clicks += 1;
console.log(`clicks: ${clicks}`);
});
}
const button = new EventTarget();
makeClickCounter(button);
button.dispatchEvent(new Event('click')); // clicks: 1
button.dispatchEvent(new Event('click')); // clicks: 2Each call to makeClickCounter creates a new clicks variable. If you attach counters to two buttons, each one counts separately.
Removing a Handler Needs the Same Function
removeEventListener only works if you pass the same function object you registered. An inline arrow function can't be removed, because you have no reference to it. A closure solves this cleanly. Return an "unsubscribe" function that remembers the handler.
function on(target, type, handler) {
target.addEventListener(type, handler);
return function off() {
target.removeEventListener(type, handler);
};
}
const button = new EventTarget();
const off = on(button, 'click', () => console.log('clicked'));
button.dispatchEvent(new Event('click')); // clicked
off();
button.dispatchEvent(new Event('click')); // (nothing)The off function closes over target, type, and handler. The caller never has to store them. Many libraries use this pattern, including React's useEffect cleanup and most observable and store APIs.
Debouncing: A Closure That Owns a Timer
Debouncing delays a function until calls stop arriving for a set time. It is commonly used for search boxes and window resize handlers. The timer ID has to survive between calls and stay hidden from other code, which makes it a good fit for a closure.
function debounce(fn, waitMs) {
let timerId = null;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, waitMs);
};
}
const log = debounce((text) => console.log('search for:', text), 200);
log('j');
log('ja');
log('jav');
// about 200 ms after the last call:
// search for: javThe returned function and the inner timer callback each close over different things. The outer wrapper captures timerId, fn, and waitMs. The arrow function inside setTimeout captures args and this from the current wrapper call. Each call gets fresh args, and all calls share one timerId.
Closures Across await
An async function pauses at each await and resumes later in a separate task. Variables declared in the function stay available after it resumes, because the rest of the function body behaves like a callback that closes over them. Shared outer variables may have changed during the wait.
You can use this to ignore stale responses. When a user types quickly, an older and slower request can finish after a newer one.
function fakeFetch(query) {
const delay = query.length * 50;
return new Promise((resolve) => {
setTimeout(() => resolve(query.toUpperCase()), delay);
});
}
function createSearch() {
let latestRequest = 0;
return async function search(query) {
const requestId = ++latestRequest;
const result = await fakeFetch(query);
if (requestId !== latestRequest) {
console.log(`ignored stale result for "${query}"`);
return;
}
console.log(`showing results for "${query}": ${result}`);
};
}
const search = createSearch();
search('javascript'); // takes about 500 ms
search('js'); // takes about 100 ms
// showing results for "js": JS
// ignored stale result for "javascript"The code relies on two different captures:
latestRequestis shared by every call. After theawait, it holds the newest ID. This is the "live value" behavior from the timer section, used on purpose.requestIdis aconstlocal to each call. After theawait, it still holds that call's ID. This is the snapshot.
Comparing the two tells you whether a newer request started while this one was waiting.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Timer logs a later value than expected | Callback reads a variable that was reassigned before it fired | Copy into a `const` or pass it as a `setTimeout` argument |
| `removeEventListener` does nothing | A new function was passed, not the registered one | Keep a reference, or return an unsubscribe closure |
| All callbacks from a loop print the same number | Loop used `var`, so every callback shares one binding | Use `let` in the loop header |
| Old async result overwrites newer data | Responses finish out of order | Track a request ID in a closure and compare after `await` |
| Handler keeps running after its component is gone | Listener was never removed, so the closure stays alive | Call the cleanup function when the owner is torn down |
The last row is also a memory concern. A registered listener keeps its whole captured environment reachable. A later chapter covers that cost in detail.
Exercises
Exercise
What does this code print, and in what order? let n = 1; setTimeout(() => console.log('a', n), 0); const m = n; setTimeout(() => console.log('b', m), 0); n = 5; console.log('c', n);
Show answer
It prints "c 5", then "a 5", then "b 1". The synchronous log runs first. The first timer reads n when it fires, after n was set to 5. The second timer reads m, a const copied while n was still 1.
Exercise
Write a function once(target, type, handler) that registers a listener, runs handler only on the first event, and then removes itself. Do not use the built-in { once: true } option.
Show answer
function once(target, type, handler) { function wrapper(event) { target.removeEventListener(type, wrapper); handler(event); } target.addEventListener(type, wrapper); } The named wrapper function closes over target, type, and handler, and it can remove itself because it has a reference to its own name.
Exercise
In the debounce example, why is timerId declared outside the returned function and not inside it?
Show answer
If timerId were declared inside the returned function, every call would create a new variable starting at null, so clearTimeout could never cancel the previous call's timer. Declaring it in the outer scope lets every call share one variable through the closure.