Skip to content

Instantly share code, notes, and snippets.

@guillaumegarcia13
Created September 18, 2019 09:54
Show Gist options
  • Save guillaumegarcia13/d4e7b292548e88c9de192a4b6da247ea to your computer and use it in GitHub Desktop.
Save guillaumegarcia13/d4e7b292548e88c9de192a4b6da247ea to your computer and use it in GitHub Desktop.
sleep (await version)
var sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Usage
// within an 'async' function
await sleep(2000);
// And without async?
// scenarios like the following do not work unfortunately
console.log('Wait for 5s...');
(async function() {
await sleep(5000);
})();
console.log('OK! Waited 5s');
// indeed, you should have an async which is precisely what you want to avoid
console.log('Wait for 5s...');
await (async function() {
await sleep(5000);
})();
console.log('OK! Waited 5s');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment