Sub topic 2
The Building Blocks: Closures, setTimeout, and clearTimeout
Debounce and throttle look like special tools, but they are built from three ordinary parts. A closure keeps state between calls. setTimeout schedules work for later. clearTimeout cancels work you scheduled. This chapter covers how each part behaves, the mistakes people commonly make with them, and how they fit together into the "reset the timer" pattern that later chapters use to build debounce and throttle.
This chapter assumes you can write functions and arrow functions, attach DOM event listeners, and know roughly what the event loop does. You don't need to know any timer internals yet.
Closures: Private State That Survives Between Calls
A closure is a function bundled with the variables that were in scope when it was created. When an outer function returns an inner function, the inner function can still read and write the outer function's variables, even after the outer function has finished running.
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
console.log(next()); // 3count is not a global variable, and it is not recreated on each call. It lives in the scope created by the single call to makeCounter, and only the returned function can reach it. Every rate-limiting wrapper relies on this. The wrapper needs to remember something between events, such as "is a timer pending?" or "when did I last run?", and a closure gives it a private place to store that.
Each factory call gets its own state
Calling the factory again creates a new, independent scope:
function makeCounter() {
let count = 0;
return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
a();
a();
console.log(a()); // 3
console.log(b()); // 1This matters later. If you wrap two different input fields with two separate calls to a debounce factory, each field gets its own timer. If you create one wrapper and share it between both fields, they share one timer, and typing in one field can cancel pending work for the other.
setTimeout: Scheduling Work for Later
setTimeout(callback, delay, ...args) asks the runtime to run callback after at least delay milliseconds. It returns immediately with a timer ID, a handle that identifies this scheduled call.
console.log('before');
const id = setTimeout(() => {
console.log('timer fired');
}, 100);
console.log('after, timer id:', id);
// before
// after, timer id: <id>
// timer fired (about 100 ms later)The code after setTimeout runs first. The callback is placed in the task queue once the delay has passed, and the event loop runs it only when the call stack is empty.
The delay is a minimum
The delay sets the earliest time the callback can run. It does not guarantee when the callback will run. Several things can push it later:
- A long synchronous task blocks the event loop, so the callback waits until that task finishes.
- Browsers clamp nested timers. Once timers are nested more than five levels deep, the minimum delay becomes 4 ms.
- Browsers throttle timers in background tabs, often to once per second or slower.
const start = Date.now();
setTimeout(() => {
console.log('elapsed:', Date.now() - start, 'ms');
}, 50);
// Block the thread for about 200 ms
while (Date.now() - start < 200) {}
// elapsed: ~200 ms, not 50For debounce and throttle this is usually fine, because you want "around 300 ms after typing stops", not microsecond precision. Still, don't write code that assumes a timer fires at an exact moment.
Timer IDs differ between environments
In browsers, setTimeout returns a positive integer. In Node.js, it returns a Timeout object. Treat the ID as an opaque value: store it and pass it back to clearTimeout, but don't do arithmetic on it or compare it to 0. If you write TypeScript that has to run in both environments, type it as ReturnType<typeof setTimeout>.
clearTimeout: Cancelling Scheduled Work
clearTimeout(id) removes a pending timer, so its callback never runs.
const id = setTimeout(() => {
console.log('you will never see this');
}, 1000);
clearTimeout(id);
console.log('cancelled');clearTimeout is forgiving in a way that makes rate-limiting code simpler. Calling it with undefined, with the ID of a timer that already fired, or with an ID that was already cleared does nothing and throws no error. So you can call clearTimeout(timerId) unconditionally, without first checking whether a timer exists.
let timerId; // undefined
clearTimeout(timerId); // safe, does nothing
timerId = setTimeout(() => console.log('fired'), 10);
setTimeout(() => {
clearTimeout(timerId); // timer already fired; still safe
console.log('cleared a finished timer without error');
}, 50);Putting Them Together: The Reset-the-Timer Pattern
Combine the three parts and you get a wrapper that keeps a timer ID in a closure, cancels the previous timer on every call, and schedules a new one. Only the last call in a quick burst survives long enough to fire.
function makeResettable(callback, delay) {
let timerId; // lives in the closure, shared by every call
return function () {
clearTimeout(timerId); // cancel the previous schedule
timerId = setTimeout(callback, delay); // start a fresh one
};
}
const ping = makeResettable(() => console.log('fired once'), 100);
ping(); // t = 0
setTimeout(ping, 50); // t = 50, resets the timer
setTimeout(ping, 90); // t = 90, resets again
// "fired once" prints at about t = 190You can run this in Node.js or a browser console. Three calls produce one callback, 100 ms after the last call.
This pattern is the core of debounce. The next chapter builds it into a complete function. Throttle uses the same closure-held state, but it stores a timestamp instead of, or alongside, a timer ID.
Common Errors
Declaring the timer inside the returned function
This is the most common bug. If timerId is declared inside the inner function, every call creates a new, empty variable, so clearTimeout never sees the previous ID.
function brokenResettable(callback, delay) {
return function () {
let timerId; // new variable on every call
clearTimeout(timerId); // always clears undefined
timerId = setTimeout(callback, delay);
};
}
const ping = brokenResettable(() => console.log('fired'), 100);
ping();
ping();
ping();
// "fired" prints three timesThe fix is to move the declaration up one level, into the factory, so all calls share it.
Creating a new wrapper on every event
The same problem shows up one level higher when the factory is called inside the handler:
const callback = () => console.log('fired');
// Wrong: a new wrapper, with a new closure, for every event
function onInput() {
makeResettable(callback, 300)();
}Each call to makeResettable creates a fresh timerId, so nothing is ever cancelled. Create the wrapper once and pass that same function to addEventListener. In frameworks that re-run component code on every render, this mistake is easy to make without noticing. A later chapter covers how to avoid it in React.
Calling the function instead of passing it
setTimeout(callback(), delay) runs callback right away and schedules its return value, usually undefined. Pass the function itself: setTimeout(callback, delay), or wrap it in an arrow function, as in setTimeout(() => callback(x), delay).
Losing this and arguments
makeResettable above ignores its arguments and calls callback with no this. For an event handler, that means the callback never receives the event object. Fixing this takes rest parameters and apply, which a later chapter covers. For now, notice that a closure captures variables only. It does not capture the arguments of each call unless you store them.
Quick Reference
| Tool | What it does | Detail that matters for rate limiting |
|---|---|---|
| Closure | Keeps variables alive between calls | State must be declared in the factory, not in the returned function |
| `setTimeout` | Schedules a callback after at least `delay` ms | Returns an opaque ID; the actual delay can be longer |
| `clearTimeout` | Cancels a pending timer | Safe to call with `undefined` or with stale IDs; does not reset your variable |
Exercise
A teammate writes function wrap(fn, ms) { return () => { const t = setTimeout(fn, ms); clearTimeout(t - 1); }; }, intending to cancel the previous timer. Name two problems with this code.
Show answer
First, t is a local constant, so the wrapper keeps no state between calls. The previous ID has to live in the closure, declared in wrap. Second, the code assumes IDs are sequential integers. Browsers don't guarantee that, and in Node.js IDs are objects, so t - 1 is NaN. Store the previous ID and pass that exact value to clearTimeout.
Exercise
Using makeResettable(cb, 100), you call the wrapper at t = 0, 120, and 150 ms. When does cb run, and how many times?
Show answer
Twice. The call at t = 0 schedules cb for t = 100. No call arrives before then, so cb runs at about t = 100. The call at t = 120 clears the old timer, which has already fired, so nothing happens, and then schedules a new one. The call at t = 150 cancels that timer and schedules another, so cb runs again at about t = 250.
Exercise
Why can you call clearTimeout(timerId) on the very first call, when timerId is still undefined?
Show answer
clearTimeout does nothing when it receives undefined or an ID that isn't valid, and it throws no error. You can therefore call it every time without checking first whether a timer exists.