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:

  1. Create a function called sleep that takes a parameter representing the number of milliseconds to sleep.
  2. Inside the sleep function, use the setTimeout function to delay the execution of a callback function by the specified number of milliseconds.
  3. 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();