How to use setTimeout in an async function with JavaScript?

Sometimes, we want to use setTimeout in an async function with JavaScript.

In this article, we’ll look at how to use setTimeout in an async function with JavaScript.

How to use setTimeout in an async function with JavaScript?

To use setTimeout in an async function with JavaScript, we can create a promise that calls setTimeout.

For instance, we write:

const wait = delay => new Promise(resolve => setTimeout(resolve, delay));

const f = async () => {
  console.log(1)
  await wait(2000);
  console.log(2)
}
f()

to define the wait function that returns a promise which calls setTimeout with resolve as the callback and after delay milliseconds.

Once resolve is called, the promise finishes running.

Next, we define the function f that calls wait between the 2 console logs.

Therefore, we see 2 logged after 2 seconds after 1.

Conclusion

To use setTimeout in an async function with JavaScript, we can create a promise that calls setTimeout.