r/badcode • • Jan 03 '21

js setTimeoutception

Post image
719 Upvotes

35 comments sorted by

View all comments

Show parent comments

10

u/[deleted] Jan 03 '21 edited Jan 03 '21

Or just recursion, with an index that's passed into the function.

Something kind of like:

const timeoutList = [1500, 3000, (full list of timeouts)];
function setTimeoutFromArr(idx, cb) {
    if (idx >= timeoutList.length) return;
    setTimeout(() => {
        cb();
        setTimeoutFromArr(idx++, cb);
    }, timeoutList[idx]);
}
setTimeoutFromArr(0, someCbFuncToRerunHere);

Untested, but hopefully you get the idea.

Edit: can't get it to format, just use the automod link I guess. It's my first time writing a code block here from mobile, sorry

1

u/AutoModerator Jan 03 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/Darkcharmer, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.