Last active
August 11, 2020 19:05
-
-
Save mike-pete/94bf741f06ee051f79221613aa5e84de to your computer and use it in GitHub Desktop.
wait.js
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
/** | |
* 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