Lesson 12 of 12 · 11 min · JavaScript in the browser
Closures and promises in real browser code
What you will learn
- See closures, scope and promises working together in real UI code
- Build a search box with debounce, cancellation and race-condition protection
- Show loading, empty and error states correctly
- Write a small cache and a tiny state store with closures
- Debug stale values, forgotten awaits and shared-variable bugs
In simple words
You have learnt the pieces: variables and scope, closures that remember, promises that arrive later, and async/await. This lesson puts them together in code like you would write at work: a search-as-you-type box that does not hammer the server, that never shows old results over new ones, and that handles slow and failing networks gracefully. Each small piece uses an idea from earlier lessons.
Words to know
- Race condition: a bug where the result depends on which of two asynchronous things finishes first.
- Stale data: old information shown after newer information is available.
- Debounce: waiting until the user pauses before doing the work.
- State: the data that describes what the interface should currently show.
Problem: a search box
We want: the user types a word; after they pause, we call /api/search?q=...; we show results, a loading message, an empty message or an error. And we must never show results for "ja" after the user has already typed "java".
Step 1: debounce is a closure
function debounce(fn, delay) {
let timer; // remembered between calls: a closure
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
timer lives in the scope of debounce, and the returned arrow function closes over it, so every keystroke can cancel the previous timer. No global variable is needed, and each call to debounce creates its own private timer.
Step 2: the naive version, and its bug
input.addEventListener("input", debounce(async (event) => {
const results = await getJson(`/api/search?q=${encodeURIComponent(event.target.value)}`);
render(results); // BUG: a slow old response can arrive after a newer one
}, 300));
If the response for "ja" takes 2 seconds and the one for "java" takes 0.5 seconds, "java" results appear first and are then overwritten by the stale "ja" results. Network order is not request order.
Step 3: cancel the old request
Keep the current AbortController in a closure variable and abort it when a new search starts:
function createSearch({ endpoint, render, showStatus }) {
let controller; // the in-flight request, private to this search
return async function search(text) {
controller?.abort(); // cancel the previous request, if any
text = text.trim();
if (!text) { render([]); showStatus(""); return; }
controller = new AbortController();
const { signal } = controller; // capture THIS request's signal in a const
showStatus("Searching...");
try {
const results = await getJson(`${endpoint}?q=${encodeURIComponent(text)}`, { signal });
render(results);
showStatus(results.length ? "" : `No results for "${text}".`);
} catch (error) {
if (error.name === "AbortError") return; // cancelled on purpose: ignore, do not show an error
showStatus("Search failed. Please try again.");
}
};
}
What happens here:
controlleris a closure variable: shared by every call of this particularsearchfunction, invisible outside.const { signal } = controllercaptures the signal of this request. If a later call replacescontroller, the earlier call still holds its own signal, which has been aborted. (If we readcontroller.signalafter theawait, we might read the new controller's signal: a classic closure-and-timing bug.)- Aborting makes the old
fetchreject with anAbortError, which we ignore. try/catchshows an error message only for real failures.
Another way, when you cannot cancel (a library call), is to ignore stale answers with a counter:
let latest = 0;
async function search(text) {
const mine = ++latest; // each call gets its own id in a const
const results = await fetchResults(text);
if (mine !== latest) return; // a newer search started: drop this result
render(results);
}
Step 4: wire it up
const search = createSearch({
endpoint: "/api/search",
render: (items) => results.replaceChildren(...items.map(renderItem)),
showStatus: (message) => { status.textContent = message; }, // a role="status" element
});
input.addEventListener("input", debounce((e) => search(e.target.value), 300));
Separate concerns: debounce decides when, createSearch decides what to fetch and show, and the render functions decide how it looks. Because createSearch takes its collaborators as arguments, you can test it with fake render and showStatus functions and a mocked fetch.
Step 5: loading, empty and error states
Every request-driven view has several states; model them explicitly rather than with scattered booleans:
// state is one of: idle, loading, success, empty, error
function view(state, data) {
switch (state) {
case "loading": status.textContent = "Loading..."; break;
case "empty": status.textContent = "Nothing found."; break;
case "error": status.textContent = "Something went wrong. Try again."; break;
default: status.textContent = "";
}
}
Use aria-busy while loading, keep previous results visible while refreshing if that is less jarring, add a Retry button on errors, and avoid layout jumps by reserving space (the performance lessons).
Step 6: caching with a closure
Do not fetch the same query twice in a minute:
function withCache(fn, ttlMs = 60_000) {
const cache = new Map(); // private to this wrapper
return async (key, ...rest) => {
const hit = cache.get(key);
if (hit && Date.now() - hit.time < ttlMs) return hit.value;
const value = await fn(key, ...rest);
cache.set(key, { value, time: Date.now() });
return value;
};
}
const cachedSearch = withCache((q, opts) => getJson(`/api/search?q=${encodeURIComponent(q)}`, opts));
A subtlety: if two calls for the same key happen at once, both miss the cache. To share the in-flight request, cache the promise itself (cache.set(key, promise)) and remove it on failure. This is what libraries such as TanStack Query do for you.
Step 7: a tiny state store
Closures can hold state and notify subscribers: the idea behind Redux, Zustand and signals.
function createStore(initial) {
let state = initial; // private
const listeners = new Set();
return {
get: () => state,
set(update) {
state = { ...state, ...(typeof update === "function" ? update(state) : update) }; // immutable update
listeners.forEach((listener) => listener(state));
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener); // returns an unsubscribe function
},
};
}
const cart = createStore({ items: [], total: 0 });
const stop = cart.subscribe((s) => (badge.textContent = s.items.length));
cart.set((s) => ({ items: [...s.items, "pen"] }));
stop(); // clean up when the component goes away
React's useState and useEffect rely on exactly these ideas (the React course returns to them).
Debugging closure and async problems
| Symptom | Likely cause |
|---|---|
| A callback logs the same (last) value for every item | var in a loop, or a variable mutated before the callback ran: use const per iteration |
| An old value is used inside a callback | the callback captured a variable that was later replaced; capture into a const, or read the current value inside |
undefined where a value was expected |
a missing await or a missing return in a .then |
| "Cannot read properties of undefined" after a fetch | data not loaded yet: handle the loading state |
| Results flash old then new | race condition: cancel or ignore stale responses |
| Handlers run twice or pile up | listeners added repeatedly without removal |
| Memory grows over time | closures capturing large objects in never-removed listeners or timers |
Tools: console.log with labels, console.table, the Sources panel with breakpoints and the Scope pane (shows the closure variables a function holds, a great way to see closures), async stack traces, and the Network panel with throttling and "Offline" to test failures.
Common mistakes
- No cancellation or staleness check on search-as-you-type.
- Reading a shared variable after an
awaitand getting a newer value than intended. - Showing an error for aborted requests.
- No loading or empty state, leaving the user with a blank screen.
- Creating a new debounced function on every call (it has no memory): create it once.
- Never unsubscribing or clearing timers.
Try it yourself
- Build the search box with
debounce,AbortControllerand status messages, using a public API or a mock server with random delays. - Prove the race condition: add a random delay to the server and remove the cancellation; then restore it.
- Use DevTools throttling ("Slow 4G" and "Offline") to see the loading and error states.
- Add
withCacheand check in the Network panel that a repeated query does not hit the server. - Write the small store and use it for a shopping cart badge, with an unsubscribe on cleanup.
Check yourself
Why does debounce need a closure?
It must remember the timer between calls so each new call can cancel the previous one; the closure keeps timer private and persistent.
What is the race condition in search-as-you-type?
Responses can arrive out of order, so an older, slower response can overwrite a newer one; cancel the old request or ignore stale responses.
Why capture signal in a const before awaiting?
The shared controller variable may be replaced by a newer request while this one is awaiting; the captured constant keeps this request's own signal.
Why model loading, empty and error states explicitly?
Every network-driven view has several states, and handling each prevents blank screens and misleading messages.
Interview questions
How would you implement search-as-you-type correctly?
Debounce the input, abort or ignore stale requests so that only the latest response updates the UI, encode the query, show loading, empty and error states, and consider caching repeated queries.
How do closures relate to React hooks and event handlers?
Handlers and effects capture the variables of the render they were created in; understanding closures explains stale-state bugs and why dependencies must be listed correctly.
How do you share an in-flight request between several callers?
Cache the promise (not just the result) keyed by the request; callers await the same promise, and remove it from the cache if it fails.
Summary
- Closures keep timers, controllers, caches and state private yet persistent: debounce, memoise, stores.
- Race conditions need cancellation (
AbortController) or a staleness check; capture per-call values inconst. - Model loading, empty and error states, and show them accessibly.
- Debug with the Scope pane, breakpoints, network throttling and careful cleanup.
Going deeper
- MDN: Closures: the fundamentals this lesson builds on.
- MDN: Using the Fetch API: aborting: cancellation in context.
- MDN: Using promises: chaining and error handling.
- MDN: Debugging JavaScript: breakpoints, console and common errors.
See how much of this you can explain
A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.