In JavaScript, there is no built-in function called sleep() to pause the execution of a program for a specified amount of time. However, you can use the setTimeout() function to achieve a similar effect.
The setTimeout() function takes two arguments: a function to execute after a specified delay, and the delay time in milliseconds. To create a sleep function, you can wrap the setTimeout() function in a Promise, and use the async/await syntax to pause the execution of the program.
Here is an example of a sleep function in JavaScript:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
This function returns a Promise that resolves after the specified delay time. You can then use it like this:
async function example() {
console.log('Before sleep');
await sleep(2000); // sleep for 2 seconds
console.log('After sleep');
}
example();
This will output "Before sleep", pause for 2 seconds, and then output "After sleep".
Comments (0)