Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Web Technology by (47.6k points)

Is there a better way to engineer a sleep in JavaScript than the following pausecomp function (taken from here)?

function pausecomp(millis) { 

var date = new Date(); 

var curDate = null; 

do { 

curDate = new Date(); 

while(curDate-date < millis);

}

This is not a duplicate of Sleep in JavaScript - a delay between actions; I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

1 Answer

0 votes
by (106k points)

Below is updated ES6/JavaScript version of sleep() which is as follows:-

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...'); 

for (let i = 0; i < 5; i++) {

if (i === 3) 

  await sleep(2000); 

console.log(i); 

 } 

demo();

Related questions

0 votes
1 answer
asked Feb 7, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+2 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...