Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.