Skip to content

Instantly share code, notes, and snippets.

@mike-pete
Last active August 11, 2020 19:05
Show Gist options
  • Save mike-pete/94bf741f06ee051f79221613aa5e84de to your computer and use it in GitHub Desktop.
Save mike-pete/94bf741f06ee051f79221613aa5e84de to your computer and use it in GitHub Desktop.
wait.js
/**
* Wrapper for setTimeout
* @param {number} timeDelay Time to wait (ms)
* @returns {promise} Empty promise that is resolved after the delay
*/
async function wait(timeDelay){
return new Promise(
resolve => setTimeout(
() => resolve(), timeDelay
)
)
}
// one line implementation
// const wait = async (timeDelay) => new Promise(resolve => setTimeout(() => resolve(), timeDelay))
// setTimeout() [non-blocking]
function original(){
setTimeout(() => console.log('original'), 5000)
}
// wait() [blocking]
async function waitBlocking(){
await wait(5000)
console.log('demo')
}
// wait() [non-blocking]
function waitNonBlocking(){
wait(5000)
.then(() => console.log('demoAlt'))
}
original()
waitBlocking()
waitNonBlocking()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment