Skip to the solution
EasyFrontendAsked in 20246 min read

Promise Timeout

2.8k views

The problem

Problem, as an interviewer would state it: "Write promiseTimeout(promise, ms) — it should resolve/reject with whatever promise does, UNLESS ms milliseconds pass first, in which case it should reject with a timeout error instead."

Examples:

Code
await promiseTimeout(fetch(url), 5000); // resolves normally if fast enough
await promiseTimeout(fetch(url), 5000); // rejects with a timeout error if too slow

Clarifying questions expected:

  • If the timeout fires, does the original (now-abandoned) promise's own eventual result matter at all, or should it just be ignored?
  • Should the timeout error be a specific, identifiable type/message, so callers can distinguish "timed out" from "the operation itself failed"?
  • Is there a real, existing building block in this bank that already solves "whichever settles first wins"?

Code / implementation expected: Yes — real, direct proof of both outcomes: a fast promise correctly beating a timeout, and a genuinely slower promise correctly triggering it.

  • async

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: promiseTimeout() correctly lets a fast promise win, and correctly times out a genuinely slower one — verified directly

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 5 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Zip Arrays

Continue