Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return promise from setTimeout #35

Closed
bluzi opened this issue Dec 19, 2018 · 5 comments
Closed

Return promise from setTimeout #35

bluzi opened this issue Dec 19, 2018 · 5 comments

Comments

@bluzi
Copy link

bluzi commented Dec 19, 2018

I find myself write the following snippet in almost any project I start:

const wait = (interval) => new Promise(resolve => setTimeout(resolve, interval))

That way I can use await wait(500) to delay the execution of the next lines of an async function by 500 milliseconds.

Since I find myself rewriting it every time, I figured it might as well be natively supported by returning a promise from setTimeout:

const f = async () => { 
  console.log(new Date().getTime())
  await setTimeout(, 200)
  console.log(new Date().getTime())
}
@pwolaq
Copy link

pwolaq commented Dec 19, 2018

How would you approach using clearInterval to cancel the timeout? (Not to mention compatibility issues as setTimeout returns a number).

@peterjwest
Copy link

It would probably work better to just add a wait function, and it could be part of a sensibly named global object rather than window/global e.g. Timer.wait(300), since this wouldn't need to support clearTimeout and wouldn't introduce any backwards compatibility issues.

@bluzi
Copy link
Author

bluzi commented Dec 19, 2018

How would you approach using clearInterval to cancel the timeout? (Not to mention compatibility issues as setTimeout returns a number).

Good point, though I'm not sure it's even needed in those cases. It's possible to add another callback to retrieve the timer (i.e. let timerId; await setTimeout(, 200, id => timerId = id)), but honestly I think it could be really helpful even if you cannot cancel it.

@littledan
Copy link
Member

This repository is intended more for standard library infrastructure, as explained in https://github.com/tc39/proposal-javascript-standard-library#scope . If you want to chat about new features, Issue #16 is intended for that.

Note that setTimeout is a web platform feature, defined in the HTML specification, not a TC39 feature. You'd be better taking up your feature request there.

@zenflow
Copy link

zenflow commented Oct 13, 2020

For anyone looking into this.. here is the relevant issue for the HTML spec whatwg/html#617

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants