How to sleep() With Promises and async/await

September 10, 2020

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));

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

await sleep(1000);

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.

Tags: ,

Categories: ,