discord.js Infinite loop occurs when function is called in response to user's message

I am currently working on a Discord bot using JavaScript. The bot is intended to send a randomly generated message when the user says anything from the array:

const wordCombos = ["word1","word2","word3","word4"];

randomText is the function that produces the randomly generated message, it uses a for loop that randomly adds words from the array to a string. The getRandom function is directly below that.

function randomText(out)
{
    var lengthOf = getRandom(2, 6);
    var words = ["random1","random2","random3","random4","random5"];
    var keySmash = "";

    for (var i=0; i < lengthOf; i++)
    {
        var wordsRandom = getRandom(0, words.length);
        keySmash += words[wordsRandom];
    }
    out(keySmash);
}

function getRandom(min, max) 
{
    return Math.floor((Math.random() * max) + min);
}

When the user sends a message with a word from the array wordCombos, it calls the function. When this occurs the infinite loop begins and the user is spammed with randomly generated messages.

client.on('message', msg => 
{
    if(wordCombos.some(word => msg.content.includes(word))) 
    {
        randomText((out) => {msg.channel.send(out);});
    }
});

I have tried using a while loop that used a boolean, however the program would either only run one time or cause an infinite loop again.

Any feedback is welcome.

171 thoughts on “discord.js Infinite loop occurs when function is called in response to user's message”

Leave a Comment