Categories
JavaScript Answers

How to Use setTimeout Sequentially in JavaScript?

Spread the love

To use setTimeout sequentially in JavaScript, we can create a promise with a callback that calls setTimeout and use it multiple times.

For instance, we can write:

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}

(async () => {
  await sleep(100)
  await sleep(200)
})()

We create the sleep function that returns a promise we create with the Promise constructor.

The callback use resolve as the callback for setTimeout .

ms is the number of milliseconds to delay the call of resolve .

Then we create an async function that calls sleep with 100 and 200 milliseconds and call it immediately.

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 *