DEV Community

Brian Barbour
Brian Barbour

Posted on

15

Making SetTimeout Async Friendly

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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay