r/JavaScriptTips • • Oct 26 '22

Recursive function keeps running even if second terminating condition is fulfilled

function attemptInitialization(func, params, dice, count = 0) {
    if (count > 10) {
        console.warn('exceeded 10 attempts 😧, try something else')
        return false;
    } else if (dice()) {
        console.log('we have dice! 😄')
        func(params);
        return false;
        // for some reason next block executes even after the "return false" statement
    } else {
        console.log('no dice 🙁, trying again')
        setTimeout(() => attemptInitialization(func, params, dice, count + 1), 300);
    }
}
4 Upvotes

4 comments sorted by

1

u/SoorajSp Oct 26 '22

pls structure your code while posting. Include code inside 3 backticks.

It will be like:

CODE

1

u/[deleted] Oct 26 '22

It's in a code block

1

u/SoorajSp Oct 26 '22

Try the "break" keyword?

1

u/[deleted] Oct 26 '22

I thought the `break` keyword is used inside loops? I don't think that will work with recursion.