javascript tutorial - [Solved-5 Solutions] JavaScript version of sleep() - javascript - java script - javascript array



Problem:

What is the JavaScript version of sleep() ?

Solution 1:

function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}

click below button to copy the code. By JavaScript tutorial team

Solution 2:

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

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two second later');
}

demo();
click below button to copy the code. By JavaScript tutorial team

Solution 3:

// sleep time expects milliseconds
function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

// Usage!
sleep(500).then(() => {
    // Do something after the sleep!
});

click below button to copy the code. By JavaScript tutorial team

Solution 4:

function sleepFor( sleepDuration ){
    var now = new Date().getTime();
    while(new Date().getTime() < now + sleepDuration){ /* do nothing */ } 
}


click below button to copy the code. By JavaScript tutorial team

Solution 5:

function doStuff()
{
  //do some things
  setTimeout(continueExecution, 10000) //wait ten seconds before continuing
}

function continueExecution()
{
   //finish doing things after the pause
}

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - JavaScript version of sleep()