Making setTimeout an async/await function

On more than one occasion I’ve wanted to wait a number of seconds in JavaScript. Normally,setTimeout() is fine for this, but what about the case when you are using async/await syntax?

Here is a handy wrapper that turns it into an async function!

async function wait(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}

And an simple example of its use, perhaps looping over some API calls but delaying a second between each (rate limiting):

async function doRequests(uris) {
  for(const uri of uris) {
    await fetch(uri);
    await wait(1000);
  }
}
Advertisements
Tagged with:
Posted in JavaScript, Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

CodingWithSpike is Jeff Valore. A professional software engineer, focused on JavaScript, Web Development, C# and the Microsoft stack. Jeff is currently a Software Engineer at Virtual Hold Technologies.


I am also a Pluralsight author. Check out my courses!

%d bloggers like this: