Sometimes, we want to run some JavaScript code after a delay.
In this article, we’ll look at how to set a time delay in JavaScript.
Use the setTimeout Method
We can use the setTimeout
method to run code after a time delay.
For instance, we can write:
setTimeout(() => {
console.log('hello world')
}, 1000);
We pass in a callback to run after the delay as the first argument.
And we pass in the delay to wait until the callback is run in milliseconds as the 2nd argument.
Now we should see 'hello world'
logged after 1 second.
Use the setTimeout Function in a Promise
We can use the setTimeout
function in a promise so that we can easily use setTimeout
multiple times sequentially.
To do this, we write:
const sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
}
`
(async () => {
console.log("Hello");
await sleep(2000)
console.log("world");
})()
We create the sleep
function which returns promise created with the Promise
constructor.
We pass in a callback that takes the resolve
function and calls setTimeout
with the resolve
function so that the promise is resolved.
ms
is the delay to wait in milliseconds until resolve
is run.
Then we can use it in the async
function below that.
So we should see 'Hello'
logged first.
Then after 2 seconds, 'world'
is logged.
Conclusion
We can run code with a time delay with the setTimeout
method.
To use it sequentially, we can wrap it in a promise.