DEV Community

Vance Lucas
Vance Lucas

Posted on • Originally published at vancelucas.com on

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.

Top comments (0)