Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *