Skip to content

Instantly share code, notes, and snippets.

@celsobessa
Created June 14, 2019 18:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celsobessa/bd675278ae44a6edc1e2d308d7f742a5 to your computer and use it in GitHub Desktop.
Save celsobessa/bd675278ae44a6edc1e2d308d7f742a5 to your computer and use it in GitHub Desktop.
sleep() equivalent for vanilla Javascript using ES6 features
// 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