Making SetTimeout Async Friendly

10/21/2020 · 1 minute read · 1 comment · 8876 views

Orginally posted on dev.to.

I love using the Async/Await syntax in ES6+ javascript. It keeps things simple and clean. I try my damndest avoid callbacks where possible in my code (unless a library I’m using expects or uses them–like with Express.js.)

I just want to say, I am by no means the author of this snippet, nor the first person to think it. Still, this is one of my favorite helper functions and I thought, why not share it–might make someone else’s life easier too.

export const asyncTimeout = (ms: number) => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
};

A simple function, that simply takes in the amount of milliseconds you wish to wait as a parameter. We then immediately return a new Promise, which is resolved when setTimeout completes.

In action, it may look like this.

async function doStuff() {
// doing stuff up here...

await asyncTimeout(1000);

// After waiting a second, continues doing stuff.
}

If anyone else has any awesome async helper functions they use, please share them!