Cut slow calls with AbortController
A saturated model server can take minutes. Set a time limit and actually cancel the request.
Write withTimeout(promiseFn, ms). Create an AbortController, call promiseFn(signal) and return its result. If it takes longer than ms, abort the signal and reject with an Error whose name is 'TimeoutError'. Any other error passes through unchanged.
You already have slowFetch(ms, { signal }), a fake request that answers 'done' after ms milliseconds and honours signal: when aborted it cancels and rejects with an AbortError. It counts cancellations in window.__aborted.
Challenges 0/4
- Returns the result when it arrives in time
- Rejects with TimeoutError when too slow
- Cancels the slow request (aborts the signal)
- Lets other errors through
async function withTimeout(promiseFn, ms) {
// 1. const controller = new AbortController()
// 2. abort it after ms with setTimeout
// 3. turn the abort into an Error named 'TimeoutError'
return promiseFn();
}
withTimeout((signal) => slowFetch(300, { signal }), 30)
.then(console.log, (e) => console.log(e.name, e.message));Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.
Why this matters
With no time limit, a request to a saturated model stays open for minutes and the interface looks frozen. Rejecting the promise is not enough: unless you really cancel the request, the server keeps generating an answer nobody will read and holds the GPU from the next one. AbortController cuts both, and Ollama stops generating when the client closes the connection. The same mechanism serves the stop button of a chat. How long a model takes on your machine, and so which limit to set, comes out of this 30-minute method.
Go deeper: the MDN reference →
This in production, with your data? Let's talk for 15 minutes →