In JavaScript, there is no built-in sleep() function like in some other programming languages. However, you can achieve a similar effect using setTimeout() or async/await with Promise.
Here's an example using setTimeout() to introduce a delay:
javascript
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
console.log("Start");
await sleep(2000); // Sleep for 2000 milliseconds (2 seconds)
console.log("End");
}
main();
In this example, the sleep() function returns a Promise that resolves after the specified number of milliseconds. The main() function is an async function that uses await to pause execution for the specified time.
You can adjust the duration passed to the sleep() function to control the delay. Keep in mind that JavaScript is single-threaded, so while using setTimeout() or async/await provides a delay, it won't block the entire program's execution.
If you're using a modern environment with support for async/await (such as Node.js or modern browsers), this approach is more convenient and readable. If you're targeting older environments or need more advanced control, you might explore libraries like bluebird or use plain setTimeout() with callbacks.
Here's an example using setTimeout() to introduce a delay:
javascript
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
console.log("Start");
await sleep(2000); // Sleep for 2000 milliseconds (2 seconds)
console.log("End");
}
main();
In this example, the sleep() function returns a Promise that resolves after the specified number of milliseconds. The main() function is an async function that uses await to pause execution for the specified time.
You can adjust the duration passed to the sleep() function to control the delay. Keep in mind that JavaScript is single-threaded, so while using setTimeout() or async/await provides a delay, it won't block the entire program's execution.
If you're using a modern environment with support for async/await (such as Node.js or modern browsers), this approach is more convenient and readable. If you're targeting older environments or need more advanced control, you might explore libraries like bluebird or use plain setTimeout() with callbacks.
Comments
Post a Comment