How to make a promise wait a couple of seconds before return with JavaScript?

Sometimes, we want to make a promise wait a couple of seconds before return with JavaScript.

In this article, we’ll look at how to make a promise wait a couple of seconds before return with JavaScript.

How to make a promise wait a couple of seconds before return with JavaScript?

To make a promise wait a couple of seconds before return with JavaScript, we can create a promise that pauses the code for a few seconds.

For instance, we write:

const wait = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds));
}

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

to define the wait function that calls setTimeout with resolve and the number of milliseconds to wait until resolve is called.

Then we can use it to pause our code before running the next line by calling wait with the delay in milliseconds.

Therefore, 2 is logged 2 seconds after 1 is logged.

Conclusion

To make a promise wait a couple of seconds before return with JavaScript, we can create a promise that pauses the code for a few seconds.