Skip to content

TIL: AbortSignal.timeout

Carlos Precioso
Jan 23, 20261 min read

or Promise timeouts, I was overworrying about doing setTimeouts with an AbortController, and cleaning them up afterwards to avoid memory leaks:

const timeoutController = new AbortController()
const timeoutHandle = setTimeout(() => timeoutController.abort(), 500)

try {
  await fetch(myUrl, { signal: timeoutController.signal })
} finally {
  clearTimeout(timeoutHandle)
}

The gods of JS smiled in my favor this week when I found out about AbortSignal.timeout (thanks to @miho.dev). It simplifies timeouts to a single call:

await fetch(myUrl, { signal: AbortSignal.timeout(500) })

Did you enjoy this article?

Recommend it — Standard Reader surfaces well-loved writing to more readers across the network.

Across the AtmosphereDiscussions