Sub topic 2
The Building Blocks: Closures, setTimeout, and clearTimeout
This chapter assumes you can write regular and arrow functions, attach DOM event listeners, and roughly know that the event loop runs queued callbacks after the current code finishes. Every debounce and throttle function later in this tutorial uses the same three parts: a closure that remembers state between calls, setTimeout to schedule work, and clearTimeout to cancel it. This chapter explains each part and the mistakes people commonly make with them.
Closures Keep State Between Calls
A closure is a function that keeps access to the variables of the scope it was created in, even after that outer function has returned. A rate limiter needs this because each call has to know what happened on earlier calls.
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counterA = makeCounter();
const counterB = makeCounter();
console.log(counterA()); // 1
console.log(counterA()); // 2
console.log(counterB()); // 1Each call to makeCounter creates a new count. counterA and counterB don't share state. Debounce and throttle work the same way: every wrapped handler gets its own private timer and timestamp.
setTimeout Schedules, clearTimeout Cancels
setTimeout(callback, delay) queues callback to run after at least delay milliseconds. It returns a timer ID right away. In browsers the ID is a number, and in Node.js it is a Timeout object. If you pass that ID to clearTimeout, the callback is removed before it runs.
const id = setTimeout(() => {
console.log('This never prints');
}, 1000);
clearTimeout(id);
setTimeout(() => {
console.log('This prints after about 500 ms');
}, 500);The delay is a minimum. The callback runs only after the current call stack is empty and earlier tasks have finished. Busy main threads and background tabs can push it later.
Combining Them: A Timer the Closure Owns
If you store the timer ID in a closure variable, later calls can find the pending timer and cancel it. This small "restartable alarm" shows the pattern without any rate-limiting logic yet:
function makeAlarm(message, delay) {
let timerId;
return {
start() {
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = undefined;
console.log(message);
}, delay);
},
stop() {
clearTimeout(timerId);
timerId = undefined;
},
isPending() {
return timerId !== undefined;
},
};
}
const alarm = makeAlarm('Wake up', 200);
alarm.start();
console.log(alarm.isPending()); // true
alarm.stop();
console.log(alarm.isPending()); // false
alarm.start(); // prints "Wake up" after about 200 msSeveral details here matter later:
- Calling
clearTimeout(undefined)is a safe no-op, sostartcan cancel without checking first. - When a timer fires, its ID is not cleared automatically. If you set
timerId = undefinedinside the callback, "is something pending?" checks stay correct. timerIdlives in the outer scope, so every call tostartsees the same variable.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Declaring `let timerId` inside the returned function | Each call gets a new variable, so nothing is ever cancelled | Declare it in the outer (factory) function |
| Calling the factory inside the event listener | A fresh closure on every event, so no shared state | Create the wrapped function once, then pass it to `addEventListener` |
| Treating the delay as exact | Timing assumptions break under load | Treat the delay as a minimum |
| Testing `if (timerId)` after the timer fired | Code reports a pending timer that already ran | Reset the ID in the callback |
Exercise
Given function make() { return function () { let id; clearTimeout(id); id = setTimeout(() => console.log('hi'), 100); }; } const f = make(); f(); f(); f();, how many times does "hi" print, and why?
Show answer
It prints three times. id is declared inside the returned function, so each call gets a new undefined variable and clearTimeout never cancels the earlier timers. If you move let id; into make, it prints once.
Exercise
Why should a timer callback set its stored ID back to undefined?
Show answer
A timer ID is not cleared when its timer fires. If the callback doesn't reset it, a check like timerId !== undefined would wrongly report that a call is still pending.