Qu'est-ce que la version JavaScript de sleep()

Mots clés : javascriptsleepjavascript

meilleur 4 Réponses Qu'est-ce que la version JavaScript de sleep()

vote vote

96

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();
await new Promise(r => setTimeout(r, 2000)); 
vote vote

83

// sleep time expects milliseconds function sleep (time) {   return new Promise((resolve) => setTimeout(resolve, time)); }  // Usage! sleep(500).then(() => {     // Do something after the sleep! }); 
vote vote

80

function sleepFor(sleepDuration){     var now = new Date().getTime();     while(new Date().getTime() < now + sleepDuration){ /* Do nothing */ } } 
function sleepFor(sleepDuration){     var now = new Date().getTime();     while(new Date().getTime() < now + sleepDuration){          /* Do nothing */      } }  function sleepThenAct(){     sleepFor(2000);     console.log("Hello, JavaScript sleep!"); }  sleepThenAct()
vote vote

67

function doStuff() {   // Do some things   setTimeout(continueExecution, 10000) // Wait ten seconds before continuing }  function continueExecution() {    // Finish doing things after the pause } 

Questions similaires