Measure what it costs to send data to a worker and how to make it nearly free. 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 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.
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.
As always, the examples are simplified to fit on a page. The production version has more error handling and logging, but the shape of the code is the same.
Questions, corrections, and war stories are welcome in the comments. Several of our best follow-up posts started as a reader pointing out something we had missed.
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.
The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.
Tim Berners-Lee, W3C Web Accessibility Initiative launch, 1997
Wrapping up
Questions, corrections, and war stories are welcome in the comments. Several of our best follow-up posts started as a reader pointing out something we had missed.
Comments 0