Last active
October 10, 2022 22:44
-
-
Save DaveBitter/f44889a2a52ad16b6a5129c39444bb57 to your computer and use it in GitHub Desktop.
Async implementation of the setTimeout function
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
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => { | |
setTimeout(() => { | |
cb(); | |
resolve(); | |
}, timeout); | |
}); | |
// Instead of nesting setTimeout functions... | |
const doStuff = () => { | |
setTimeout(() => { | |
// Do stuff | |
setTimeout(() => { | |
// Do more stuff | |
setTimeout(() => { | |
// Do even more stuff | |
}, 2000); | |
}, 500); | |
}, 1000); | |
}; | |
doStuff(); | |
// await them in an async function | |
const doStuffAsync = async () => { | |
await setAsyncTimeout(() => { | |
// Do stuff | |
}, 1000); | |
await setAsyncTimeout(() => { | |
// Do more stuff | |
}, 500); | |
await setAsyncTimeout(() => { | |
// Do even more stuff | |
}, 2000); | |
}; | |
doStuffAsync(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment