Discord bot memory issues when processing multiple dice roll parameters

I built a Discord bot that handles dice rolling commands like ‘roll 2d8’ or ‘roll 3d12 1d4’. It works fine with single dice commands but crashes with memory overflow when I pass multiple dice arguments.

I’m still learning JavaScript and can’t figure out what’s wrong. I suspect the issue is in my nested loop structure:

for (j = 1; j < arguments.length; j++) {
    if(arguments[j].includes('d')) {
        var diceArray = arguments[j].split('d');
        for (j = 0; j < diceArray[0]; j++) {
            resultMessage += generateRandom(diceArray[1]) + ' ';
        }
        resultMessage += '`\n';
    }
}

The bot freezes completely when handling multiple parameters. Any ideas what might be causing this memory problem?

Your problem is a variable scope conflict. The outer loop uses j to go through arguments, but the inner loop overwrites that same j starting from 0. This creates an endless cycle - the outer loop never moves past the first dice argument because j keeps getting reset. I’ve seen this cause memory leaks in other bots. The generateRandom function runs forever until the process crashes. Easy fix: rename your inner loop variable to roll or count. Also add validation to check if diceArray[0] is reasonable before the loop starts. Otherwise someone could crash your bot with ‘999999d6’.

You’re reusing the same variable j in both loops. When the inner loop starts, it resets j to 0, creating an infinite loop since j will always be less than arguments.length. Your bot generates endless random numbers until it runs out of memory. Just change one loop variable to i or k. I made this exact mistake on my first Discord bot - took me hours to figure out why it kept crashing on simple commands.