Categories
JavaScript Answers

How to Use setTimeout in JavaScript Promise Chain?

Spread the love

We can create a function that returns a promise that calls setTimeout so that we can use setTimeout in a promise chain.

For instance, we can write:

const delay = (t, v) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(v), t)
  });
}

(async () => {
  const one = await Promise.resolve(1)
  console.log(one)
  const two = await delay(1000, 2)
  console.log(two)
  const three = await Promise.resolve(3)
  console.log(three)
})()

to create the delay function that returns a promise by creating one with the Promise constructor.

We pass in a callback that calls setTimeout , which calls resolve with v and delays the execution of the callback by t milliseconds.

Then we use delay in an async function with other promises.

Now we should see a delay when we’re calling delay .

And 1, 2, and 3 are logged in the console log.

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 *