How to Sleep/Wait/Pause on a NodeJs Function

Posted on September 6, 2019 at 10:47 am

I found this example code that shows how to sleep in NodeJs:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
 
async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two seconds later, showing sleep in a loop...');
 
  // Sleep in loop
  for (let i = 0; i < 5; i++) {
    if (i === 3)
      await sleep(2000);
    console.log(i);
  }
}
 
demo();

Works perfectly and it actually sleeps by waiting/pausing the function!

References:

https://stackoverflow.com/a/39914235

Receive updates via email

Other Posts

Updated Posts