Sometimes, we want to use setTimeout
sequentially in JavaScript.
In this article, we’ll look at how to use setTimeout
sequentially in JavaScript.
Use setTimeout Sequentially in JavaScript
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.
Conclusion
To use setTimeout
sequentially in JavaScript, we can create a promise with a callback that calls setTimeout
and use it multiple times.