Fix a Stale Closure Holding an Old Value
Fix a JavaScript closure that keeps reading an old value inside a timer, listener or callback, by finding what it captured and changing how it reads it.

There is no error message for this bug, which is what makes it expensive. A timer logs 0 forever while the counter on screen says 7. An event listener compares against the filter you had when the page loaded. A callback sends the previous request's id. Nothing throws, the code reads correctly, and the value is simply old. This post explains on Node.js 24 and current browsers why a closure keeps an old value, how to recognize the five shapes the bug takes, and the four fixes that work: read from a mutable holder, pass the value as an argument, recreate the closure when the value changes, and remove the closure altogether. Every example includes the output you will see. For the background on how closures capture variables, see closure use cases in everyday code.
What a stale closure is
A closure remembers the variable, not a copy of its value at that moment. That sounds like it would prevent stale reads, and it does when the variable is reassigned in the same scope. The trouble starts when a new scope is created each time something changes, and an old callback is still holding the previous scope.
function makeLogger(value) {
return () => console.log("value is", value);
}
let current = 1;
const log = makeLogger(current);
current = 2;
log();
const logAgain = makeLogger(current);
logAgain();value is 1
value is 2makeLogger(current) copies the number into its parameter value. Later changes to current cannot reach the parameter, because primitives are passed by value. The first logger is stale from the moment it is created. The second is correct, but only because it was created after the change. Every stale closure bug is a version of this: a function was created at one moment and called at another, and the world changed in between.
Shape 1: a timer that captured a loop variable or a parameter
The classic version is a setInterval that reads a value fixed when the interval was started.
function startCounter(start) {
let count = start;
const timer = setInterval(() => {
count += 1;
}, 10);
setTimeout(() => clearInterval(timer), 55);
return { read: () => count, snapshot: start };
}
const counter = startCounter(0);
await new Promise((resolve) => setTimeout(resolve, 80));
console.log(counter.read(), counter.snapshot);5 0read is fine, because it reads the live variable count. snapshot is a primitive copied into the returned object at creation, so it will say 0 forever. The mistake is returning a value where a getter was needed. If callers need the live number, hand them a function or define a getter.
function startCounter2(start) {
let count = start;
const timer = setInterval(() => (count += 1), 10);
setTimeout(() => clearInterval(timer), 55);
return {
get count() {
return count;
},
};
}
const live = startCounter2(0);
await new Promise((resolve) => setTimeout(resolve, 80));
console.log(live.count);5Shape 2: an event listener registered once
A listener added at startup closes over whatever was in scope at that time. If the value it needs changes later, the listener never sees it.
import { EventEmitter } from "node:events";
const bus = new EventEmitter();
let filter = "all";
function setup(currentFilter) {
bus.on("item", (item) => {
console.log(`checking ${item} against ${currentFilter}`);
});
}
setup(filter);
filter = "paid";
bus.emit("item", "order-1");checking order-1 against allThe listener received filter as an argument, so it holds "all" regardless of what the outer variable becomes. If the listener had read filter directly instead of through a parameter, it would see "paid". The difference between the two is where the copy happens. Reading the outer variable directly reads the live binding; taking it as a parameter freezes it.
const bus2 = new EventEmitter();
const state = { filter: "all" };
bus2.on("item", (item) => {
console.log(`checking ${item} against ${state.filter}`);
});
state.filter = "paid";
bus2.emit("item", "order-1");checking order-1 against paidKeeping the changing value in an object that the listener reads at call time is the most common fix, and it is the same idea as a React useRef or a store with a getState() method.
Shape 3: a debounced or throttled function that captured its inputs
Wrapping a function in a debounce creates a closure once. If you wrap a new function on every change, you also create a new timer on every change, and the old timers still fire with old values.
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
let query = "a";
const search = debounce(() => console.log("searching for", query), 20);
search();
query = "ab";
search();
query = "abc";
await new Promise((resolve) => setTimeout(resolve, 50));searching for abcThis works because the debounced function reads query when it finally runs. It would be stale if query were passed in as an argument at the first call. A debounce keeps the latest arguments, so the safe pattern is to pass the value into the debounced call each time, not to capture it when the debounce was built.
const search2 = debounce((text) => console.log("searching for", text), 20);
search2("a");
search2("ab");
search2("abc");
await new Promise((resolve) => setTimeout(resolve, 50));searching for abcShape 4: async work that outlives the state it started with
A request starts, the user changes the input, the first request returns late and writes its result over the newer one. The closure is not stale about a variable, it is stale about which request is current.
let latest = 0;
async function load(id, delay) {
const mine = ++latest;
await new Promise((resolve) => setTimeout(resolve, delay));
if (mine !== latest) {
console.log(`discarding result for ${id}`);
return;
}
console.log(`showing result for ${id}`);
}
load("first", 40);
load("second", 10);
await new Promise((resolve) => setTimeout(resolve, 80));showing result for second
discarding result for firstEach call remembers its own number in mine and compares it with the shared counter after the await. The older call finds the counter has moved on and gives up. A better form for network work is an AbortController that cancels the old request, but the counter check is portable and shows the principle: compare against current state after every await.
Shape 5: a framework hook that did not list a dependency
Frameworks that rerun a function on every update, and keep effects across updates, make stale closures routine. In React, an effect with an empty dependency list runs once and keeps the first render's variables.
function simulateEffect(deps, compute) {
let cleanup = compute(deps);
return { rerun: (newDeps) => compute(newDeps), cleanup };
}
let count = 0;
const first = () => console.log("count seen by effect:", count);
count = 5;
first();count seen by effect: 5That plain closure reads the live variable, so it is not stale. In React each render has its own count, which is why the same code goes stale there. The real component version looks like this, shown for reading since it needs a React runtime.
function Ticker() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
console.log(count); // always 0
setCount(count + 1); // always sets to 1
}, 1000);
return () => clearInterval(id);
}, []);
}The effect runs once, so the callback closes over the first render's count, which is 0. Two fixes work. Use the updater form, setCount((c) => c + 1), which does not need the current value. Or list count in the dependency array, so the effect is torn down and recreated when it changes. A ref works too when you want the interval to survive: store the latest value in ref.current and read it inside the callback.
The four fixes
Pick by what the closure needs.
Read a live holder. Put the changing value in an object, a ref or a store, and read it inside the callback. The closure holds the holder, which never changes, and the holder holds the current value.
Pass the value as an argument. The caller supplies the value at call time. Debounce,
emitandsetStateupdaters all work this way.Recreate the closure when the value changes. Remove the old listener and add a new one, or let the framework rerun the effect through its dependency list. This costs a teardown but keeps the closure simple.
Remove the closure. If a method on an object can read
this.value, you may not need a closure at all.
class Poller {
interval = 10;
ticks = 0;
start() {
this.timer = setInterval(() => {
this.ticks += 1;
}, this.interval);
}
stop() {
clearInterval(this.timer);
}
}
const poller = new Poller();
poller.start();
await new Promise((resolve) => setTimeout(resolve, 35));
poller.stop();
console.log(poller.ticks);3The arrow function reads this.ticks at call time, so nothing is stale. The count printed depends on timer scheduling, and 3 is the typical result for 35 ms at a 10 ms interval; it can be 2 or 3 on a loaded machine.
How to confirm a closure is stale
Look for a function that is created once and called many times, and ask what it reads. Variables from the outer scope are live. Parameters, destructured values and copies of primitives are frozen at creation. Log the value inside the callback and next to it the value from the source of truth. If they differ, you have a stale closure, and the question becomes where the copy was made.
Do not fix this by making the value global. A global is a live holder, so it works, but it couples every function to one piece of state and makes tests order-dependent. A small object passed explicitly is the same fix without the coupling.


