BACK
Use casesTimeout fallback — the API hangs
Use cases · 30

Timeout fallback — the API hangs

Pattern

An external API hangs. Maybe overloaded. Maybe a temporary network problem. We can't wait forever — the screen shouldn't show loading endlessly. After N seconds we show cached data or a message.

The problem it solves

An imperative setTimeout around fetch is hard to cancel, and it's easy to get a double resolve: the timeout fired AND the late response arrived after all. Which value do you apply?

Operators and why they matter

  • timeout({ first: 30 }) — if the first response doesn't arrive within 30ms, it emits an error.
  • catchError — catches the timeout error and returns a fallback Observable.
  • of(fallback) — hands over a cached value or a default.

Gotchas

  • takeUntil(timer(N)) instead of timeout — just completes, no error. The UI won't show the fallback, because there was no error.
  • Too short a timeout — you'll get false timeouts on slow mobile networks.
  • Don't retry a timeout forever — it would multiply the load on an already-overloaded API.

What you get

A hung API becomes a predictable fallback. The user sees at least something, not a spinner that spins forever.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...