supersonicshin
supersonicshin

Reputation: 1

Message collector in while loop

I am trying to make a discord bot that has a "number guessing game" feature.
When I run the bot, it gives me this error:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

It seems like the while loop became an infinite loop. This is my code (all the functions and variables are declared)

while (numberOfGuesses < 5) {
  const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
    time: 10000,
    max: 1
  });
  collector.on('collect', message => {
    if (guess.length == 0 || !guessInRange(guess)) {
      message.channel.send('please say 1~100');
    } else {
      if (parseInt(guess) == secretNumber) {
        message.channel.send('Boom! Correct!');
        return collector.stop();
      } else if (parseInt(guess) < secretNumber) {
        numberOfGuesses++;
        message.channel.send('Too small');
        collector.stop();
      } else {
        numberOfGuesses++;
        message.channel.send('Too big');
        collector.stop();

      }
      if (numberOfGuesses == 5) {
        collector.stop();
        return message.channel.send('Game over');
      }
    }
  });
}

Upvotes: 0

Views: 1331

Answers (1)

Frustrated programmer
Frustrated programmer

Reputation: 721

the reason is cause the while loop runs really fast. While the messages come in slow. So by the time 5 "guesses" come, the loop could've ran a million times. therby making a million collectors as well.

try this:

function getGuesses(numberOfGuesses,maxGuesses){
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, { time: 10000, max: 1 });
    collector.on('collect', message => {
        if (guess.length == 0 || ! guessInRange(guess)) {
            message.channel.send('please say 1~100');                
        } else {
            if (parseInt(guess) == secretNumber) {
                message.channel.send('Boom! Correct!');
                return collector.stop();
            } else if (parseInt(guess) < secretNumber) {
                numberOfGuesses++;
                message.channel.send('Too small');
                collector.stop();
            } else {
                numberOfGuesses++;
                message.channel.send('Too big');
                collector.stop();

            }
            if (numberOfGuesses == maxGuesses) {
                collector.stop();
                return message.channel.send('Game over');
            }
        }   
    });

    //Repeat if guesses still exist
    collector.on('end', collected => {
        if(numberOfGuessed < maxGuesses) getGuesses(numberOfGuesses,maxGuesses)
    });
};

getGuesses(0,5);

Upvotes: 2

Related Questions