DEV Community

Vance Lucas
Vance Lucas

Posted on • Originally published at vancelucas.com on

1

How to sleep() With Promises and async/await

Occasionally you may find the need to sleep for a bit or use setTimeout in your code or your test suite if some async work is going on that you know will finish during that time (like a quick deferred function or something like that). Here’s an easy way to do it:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
Enter fullscreen mode Exit fullscreen mode

And now you can use it wherever you need to like so:

await sleep(1000);
Enter fullscreen mode Exit fullscreen mode

Caveat : Keep in mind that generally random setTimeout calls are a code smell – ideally you would know what you are waiting on and chain things up to happen after that work is done, or orgainze your code so that you know what you are waiting on specifically. This sleep method is for those times where that is not possible.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

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.

Learn more

👋 Kindness is contagious

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

Okay