sleep in nodejs?
To implement a sleep function in Node.js, you can use the setTimeout
function to delay the execution of a piece of code. Here's how you can do it:
- Create a function called
sleep
that takes a parameter representing the number of milliseconds to sleep. - Inside the
sleep
function, use thesetTimeout
function to delay the execution of a callback function by the specified number of milliseconds. - The callback function can be an empty arrow function or a function that performs a specific action.
For example:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
console.log('Hello');
await sleep(2000); // Sleep for 2 seconds
console.log('World');
}
main();