Common Closure Patterns: Debounce, Throttle, and Memoization
Debounce, throttle, memoization, and the "once" pattern — four utilities built the same way: a function closing over private state only it can see.
Common Closure Patterns: Debounce, Throttle, and Memoization
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Debounce, throttle, memoization, and "once" are all the same shape: a factory function runs a single time, creates some private state (a timer ID, a last-run timestamp, a cache, a flag), and returns a new function that closes over that state — exactly the mechanism from the closures lesson, aimed at a concrete problem.
- Debounce resets a timer on every call and only actually runs the wrapped function once calls stop arriving for a quiet period — correct for a search-as-you-type box, where you want one API call after the user stops typing, not one per keystroke.
- Throttle guarantees at most one call gets through per fixed time window, no matter how many times the wrapped function is invoked inside it — correct for a scroll or `mousemove` handler, where you want steady, capped-rate updates, not silence followed by one delayed burst.
- Memoization caches a function's return value keyed by its arguments, so a second call with the same inputs returns the cached result instead of recomputing it — a straightforward trade of memory for time, and it only pays off for functions whose output depends purely on their input.
- The "once" pattern guarantees a function's real logic executes on only the very first call, using a closed-over flag to detect every call after that and skip the work (optionally returning whatever the first call produced) — useful for one-time setup code that must never run twice, even if something calls the wrapper repeatedly by mistake.
Same mechanism, four different jobs
The closures lesson covered the mechanism: an inner function keeps access to an outer function’s local variables, even after the outer function has finished running. This lesson is about four concrete things people actually build with that mechanism — debounce, throttle, memoization, and the “once” pattern. Each one follows the identical shape: a factory function runs exactly once, sets up some private state that nothing outside can reach directly, and hands back a new function that reads and updates that state on every call. The pattern doesn’t change; only what’s sitting in the closure does — a timer ID, a timestamp, a cache, a flag.
Debounce: wait until things go quiet
A search-as-you-type box firing a network request on every keystroke is wasteful — if someone types “cat” in half a second, that’s potentially three requests when only the last one (the complete word) matters. Debounce fixes this by resetting a timer every time it’s called, and only actually running the real function once the calls stop coming for a set delay:
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}
const debouncedSearch = debounce(runSearch, 300);
timeoutId is the private state. Every call to the debounced function
cancels whatever timer the previous call started and schedules a new
one — so as long as calls keep arriving faster than the delay, the real
fn never runs at all. It only fires once there’s a 300ms gap with no
new calls, which is exactly the “user stopped typing” moment a search box
wants to react to.
Throttle: no more than once per interval
Debounce would be the wrong tool for a scroll handler that updates a “reading progress” bar — if it waited for scrolling to stop before updating even once, the bar would sit frozen during continuous scrolling and only catch up afterward. Throttle solves a different problem: let calls through at a capped, steady rate instead of waiting for silence.
function throttle(fn, interval) {
let lastRun = 0;
return function (...args) {
const now = Date.now();
if (now - lastRun >= interval) {
lastRun = now;
fn(...args);
}
};
}
const throttledUpdate = throttle(updateProgressBar, 100);
Here the private state is lastRun, a timestamp. Every call checks how
long it’s been since the last time fn actually ran; if enough time has
passed, it runs again and updates the timestamp — otherwise the call is
simply dropped. The result is a function that fires at most once every
100ms no matter how many times it’s invoked, which keeps a continuously
firing event like scroll or mousemove from flooding whatever it’s
driving.
Memoization: don’t recompute what you already know
Some functions are expensive to run but always return the same output for the same input — a heavy calculation, a recursive algorithm with overlapping subproblems. Memoization trades memory for time by caching each result the first time it’s computed:
function memoize(fn) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
}
const fastCompute = memoize(expensiveComputation);
The Map is the private state — created once, then read and written on
every call, invisible to anything outside. The precondition matters:
memoization is only correct for a pure function, one whose result
depends solely on its arguments. Memoize something that also depends on
the current time or a database row that can change, and the cache will
happily return a stale answer forever.
The once pattern: logic that can’t run twice
Some operations — one-time setup, firing an analytics event, initializing a resource — must execute exactly once even if something calls the wrapper repeatedly by accident. The once pattern uses a closed-over flag to tell the first call apart from every call after it:
function once(fn) {
let hasRun = false;
let result;
return function (...args) {
if (!hasRun) {
hasRun = true;
result = fn(...args);
}
return result;
};
}
const initialize = once(setUpApp);
hasRun and result are both private state the returned function can
see and the caller never can. Call initialize() five times, and
setUpApp genuinely runs only on the first call — every call after that
just hands back the result that was already computed, skipping the real
work entirely.
Where this fits
All four patterns are proof that closures aren’t an abstract rule you learn once and forget — they’re the actual mechanism behind utilities you’ll reach for constantly, from a search box to a scroll listener to an expensive calculation you don’t want to repeat. The next lesson, IIFEs and the module pattern, leans on this same idea of closures hiding private state, applied to an entire chunk of code instead of a single returned function.
Check yourself
What single mechanism makes debounce, throttle, and memoization all possible, and where does it come from?
All three are a function that runs once, creates a local variable (a timer, a timestamp, a cache object), and returns a new function that keeps reading and writing that variable on every call. That's a closure: the returned function keeps access to the outer function's local state even though the outer function itself only ran once, at setup time.
A search box calls a debounced `search` function on every keystroke, with a 300ms delay. The user types "cat" quickly. How many times does the real search actually run, and when?
Once — about 300ms after the last keystroke (typing the final "t"), not once per letter. Each keystroke resets the pending timer before it can fire, so as long as keystrokes keep arriving faster than 300ms apart, nothing actually runs; the real call only fires once input goes quiet for the full delay.
Why is throttle the correct choice for a scroll handler, where debounce would be the wrong one?
A debounced scroll handler would wait for scrolling to stop entirely before running even once, so anything meant to update continuously — like a progress indicator — would sit frozen mid-scroll and only catch up after the user stops. Throttle instead lets a capped number of updates through at a steady rate *during* the scroll, which is what a continuously-updating UI actually needs.
Why does memoization only make sense for a function whose return value depends purely on its arguments?
The cache is keyed on the arguments alone — call it again with the same arguments, and the cached result gets returned without re-running the function. If the function's result also depends on something else (the current time, a mutable global, a network response that can change), the cached value can go stale and silently return a wrong answer for inputs that no longer map to that output.
How does the "once" pattern guarantee a function's setup logic never runs twice, even if the returned function gets called five times?
The closure keeps a flag (and usually the first call's return value) in its private state. The very first call runs the real logic and flips the flag; every call after that checks the flag first, sees it's already been run, and returns the stored result (or does nothing) instead of executing the logic again — the flag is invisible to and untouchable by whatever is calling the wrapped function.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.