How Can I Wait in Node.js? l Need to Pause for a Period of Time

Approach 1

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

console.log('Welcome to my console,');
sleep(10000);
console.log(‘Other information after sleep’');

Approach 2

async function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function main() {
  console.log("Start");
  await sleep(2000); // Sleep for 2 seconds
  console.log("End");
}
main();

Subscribe for
weekly updates

newsletter