Cancel stale requests, add timeouts, and clean up listeners with one small object. JavaScript gives you a dozen ways to solve the same problem, and the platform quietly added a better one while most of us were not looking. This post walks through that better way and the reasoning behind it.
The problem in one snippet
The first version of our code worked on a fast laptop and failed on a slow phone. Nothing was wrong with the logic; the timing assumptions were simply never written down, so nobody noticed when they stopped being true.
export async function fetchWithTimeout(url, { timeout = 8000, ...options } = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { ...options, signal: controller.signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} finally {
clearTimeout(timer);
}
}
Wiring it into real code
Once the pattern is in place, the rest of the codebase gets simpler. Callers no longer need to remember cleanup, and the error paths are handled in one spot instead of five.
- Measure on a throttled CPU, not your laptop.
- Clean up listeners in the same place you add them.
- Treat every network call as cancellable.
- Log the slow path, not just the error path.
Edge cases we hit
Keep an eye on older browsers and on Node versions below 18, where some of these APIs are missing or behind flags. A tiny feature check at startup saves a confusing bug report later.
We will revisit this in six months with fresh numbers. If the results change, we will update the post and note what changed at the end.
If you try this on your own project, start with one page or one service rather than the whole codebase. A small experiment gives you real numbers to argue with, and it is easy to roll back if the idea does not fit.
We have been running this approach for several months now. The initial setup took about a day, and the ongoing cost is close to zero once the team knows where to look.
Before you ship this
An aborted fetch rejects with an AbortError. Catch it separately so a cancelled request is not reported as a failure in your error tracker.
Adding manpower to a late software project makes it later.
Fred Brooks, The Mythical Man-Month, 1975
Wrapping up
None of this is new, and that is the point. The techniques that last are usually the boring ones that are documented well and supported by the platform itself.
Clear, practical, no fluff. More of this, please.
Same experience here, the tooling is much better now.
How does this hold up on older Safari versions? That is where we always get burned.
It should work without shell access, you just lose the command-line shortcuts.
Great post. Did you measure the impact before and after, or is this mostly from experience?
Clear, practical, no fluff. More of this, please.
We tried something similar in 2023 and rolled it back. Curious whether the tooling has caught up since.