Html: Promise returning version of `setTimeout`

Created on 2 Aug 2018  路  3Comments  路  Source: whatwg/html

With the popularity of async/await in JavaScript and the adoption of DOM futures (promises) across new DOM APIs one pretty common request I've ran into is a promise returning version of setTimeout.

This can either be achieved by overloading setTimeout or exposing a new method that returns a promise:

await delay(3000); // similar to `new Promise(r => setTimeout(4, 3000))`

Ideally, it wouldn't have the string-as-parameter behaviour. One argument against this is that while it's common it's also pretty easily implemented (with the promise constructor). This is true - though I've seen people make mistakes implementing it and it's so common it might make sense to ship it from the platform.

Node also added a util.promisify.custom on setTimeout so it's easy to get a version of setTimeout that does this in Node.

I'm not really decided myself - I'm mostly asking for this because of API discussions on a new platform that needs timers and the fact I'd rather go with a specified standard than without one - it seems weird to add setTimeout as specified in the timers spec taking a callback.

additioproposal needs implementer interest

Most helpful comment

I'm somewhat ambivalent, but any such API probably also needs something equivalent to clearTimeout(). Maybe using AbortSignal/AbortController.

Sure, what if we allow passing an AbortController.signal as an optional second parameter?

await delay(3000, { signal: controller.signal} );

In a way similar to fetch?

Another interesting idea is a variant of setInterval that returns an async iterator, though we might not want to tie the two together.

for await(const time of interval(1000)) {
 // do something, `break` here to cancel (or `.return` on the iterator)
}

All 3 comments

I'm somewhat ambivalent, but any such API probably also needs something equivalent to clearTimeout(). Maybe using AbortSignal/AbortController.

I'm somewhat ambivalent, but any such API probably also needs something equivalent to clearTimeout(). Maybe using AbortSignal/AbortController.

Sure, what if we allow passing an AbortController.signal as an optional second parameter?

await delay(3000, { signal: controller.signal} );

In a way similar to fetch?

Another interesting idea is a variant of setInterval that returns an async iterator, though we might not want to tie the two together.

for await(const time of interval(1000)) {
 // do something, `break` here to cancel (or `.return` on the iterator)
}

Let's dupe this into https://github.com/whatwg/html/issues/617, which already has some discussion on cancelation.

Was this page helpful?
0 / 5 - 0 ratings