A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

Promise.delay (sleep) and Promise.timeout

Jack-Works
2020-07-11
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. https://es.discourse.group/t/promise-delay-sleep-and-promise-timeout/349

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.

isiahmeadows
2020-07-12

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.
domenic
2020-07-14

See https://github.com/whatwg/html/issues/617 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 https://github.com/whatwg/dom/issues and working toward implementer interest. This was previously discussed a bit in https://github.com/whatwg/fetch/issues/951#issuecomment-541369940. Again, I am happy to specify this if we have any implementation interest.

Jack-Works
2020-10-02

Hi! @domenic My spec writes:

The interpretation of afterTime is depending on the host. Host can return AbortCompletion if the environment does not allow clock-dependent behaviors or afterTime is invalid value.

With this spec text, it is possible to “certain host environments, like worklets, want to prevent clock-dependent behavior