Created
June 14, 2019 18:30
-
-
Save celsobessa/bd675278ae44a6edc1e2d308d7f742a5 to your computer and use it in GitHub Desktop.
sleep() equivalent for vanilla Javascript using ES6 features
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sleep() equivalent for vanilla Javascript using ES6 features | |
// created by Dan Dascalescu | |
// see https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep/39914235#39914235 | |
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment