Skip to content

Instantly share code, notes, and snippets.

@DaveBitter
Last active October 10, 2022 22:44
Show Gist options
  • Save DaveBitter/f44889a2a52ad16b6a5129c39444bb57 to your computer and use it in GitHub Desktop.
Save DaveBitter/f44889a2a52ad16b6a5129c39444bb57 to your computer and use it in GitHub Desktop.
Async implementation of the setTimeout function
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