Promise.delay (sleep) and Promise.timeout

await Promise.delay(2000)
// resolves after _at least_ 2000 ms, same as setTimeout
await Promise.timeout(fetchTaskPromise, 2000)
// rejects after 2000ms if fetchTaskPromise not resolved

I previously posted this in tc39 discussion.

But it’s hard to specify it in the ES spec so I post this in WICG hope we can use it in the Web.

Like the idea, but I have a couple suggestions:

  1. This should be attached to the window, not Promise, to align with other DOM APIs.
  2. I’m not convinced we should have a separate .delay and .timeout - that’s just Promise.race([fetchTaskPromise, delay(2000)]). Instead, this should really integrate with AbortSignal somehow.

See for the Promise.delay equivalent.

I am happy to specify this if we have any implementation interest. (And I agree it would be on Window, or more likely WindowOrWorkerGlobalScope, not on Promise. Another reason is that certain host environments, like worklets, want to prevent clock-dependent behavior, so having this in the language would be bad.) It would also be abortable using AbortSignal, per the above-linked thread.

For your Promise.timeout, I suggest AbortSignal.timeout(2000), used like so:

fetch(url, { signal: AbortSignal.timeout(2000) })

(maybe AbortSignal.after would be a reasonable name too.) For that, the next step would be filing an issue on and working toward implementer interest. This was previously discussed a bit in Again, I am happy to specify this if we have any implementation interest.

1 Like