DEV Community

loading...

Making SetTimeout Async Friendly

steelvoltage profile image Brian Barbour ・1 min read

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);
  });
};
Enter fullscreen mode Exit fullscreen mode

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.
}
Enter fullscreen mode Exit fullscreen mode

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

Discussion (1)

pic
Editor guide
Collapse
dannysmc95 profile image
Danny SMc

Agreed, async/await I think has been the kick JavaScript always needed, makes your code look much cleaner! But this snippet is the most used snippet I think I have ever used, in pretty much every application I always have some form of async based timeout function!