
JavaScript sleep
The JavaScript is no built-in sleep function like in some other programming languages. JavaScript is designed to be single-threaded and focuses on asynchronous, non-blocking operations.
However, you can achieve a similar effect by using a combination of setTimeout or setInterval functions and Promises or async/await syntax. Here’s an example using setTimeout:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Usage:
console.log('Start');
await sleep(2000); // Sleep for 2 seconds
console.log('End');
In the code above, the sleep
function returns a Promise that resolves after the specified number of milliseconds. By using the await
keyword before sleep
, you can pause the execution of the code for the given duration.
Please note that the await
keyword can only be used within an async
function, so you would need to wrap your code inside an async
function or use it in a context that supports async/await
.
Alternatively, you can use libraries or frameworks like async
or bluebird
that provide more advanced control flow mechanisms, including sleep-like functionality. These libraries offer additional features and utilities for managing asynchronous operations in JavaScript.