JavaScript does not have a built-in “sleep()” function that pauses the code execution for a specified period of time. But you can use methods such as setTimeout() for delaying execution and async/await for creating pauses in asynchronous functions.
Using setTimeout()
You can intentionally delay function execution by combining setTimeout() and and Promise.
Syntax
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
Example
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
const list = [1, 2, 3, 4]
const task = async () => {
for (const item of list) {
await sleep(1000);
console.log('Hello AppDividend');
}
}
task();
The above statements will be logged one by one after a 1-second delay.
If you don’t want to define the sleep() function, still you can achieve the same output.
const list = [1, 2, 3, 4]
const task = async () => {
for (const item of list) {
await new Promise(r => setTimeout(r, 1000));
console.log('Hello AppDividend');
}
}
task();
Output
Hello AppDividend
Hello AppDividend
Hello AppDividend
Hello AppDividend
But again, it depends on what you are trying to achieve and ensure the application’s performance.
Using async/await for Sleep in Asynchronous Functions
In an async function, you can then use the await keyword with the sleep function to pause the function execution for the given amount of time.
Syntax
async function sleep(milliseconds) {
await new Promise(resolve => setTimeout(resolve, time));
}
Example
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function task() {
console.log("Before sleep");
await sleep(3000); // Sleep for 3 seconds
console.log("After 3 second");
}
task();