0

I am using discord.py to make a Discord bot that gives you a complement every 24 hours. To test, I set the timer to 1 second. The code I made looked like this:

const Discord = require('discord.js')
const client = new Discord.Client()

const complements = [
    ...
]

client.once('ready', () => {
    console.log('Logged in!');
    client.user.setActivity("with nice complements.")
    setInterval(console.log,1000,complements[Math.floor(Math.random() * (complements.length - 1))]);
});

However, this just returns the same complement every time. Is there any ways it can choose a random complement?

2
  • 1
    Is that discord.py or discord.js? Commented May 21, 2020 at 19:31
  • @Pepe_Worm discord.js Commented May 21, 2020 at 19:32

4 Answers 4

2

The parameters you pass to setInterval are evaluated at the time when you pass them to the setInterval function not at each execution of it.

So this: setInterval(console.log,1000,complements[Math.floor(Math.random() * (complements.length - 1))]);

is equal to:

let complement = complements[Math.floor(Math.random() * (complements.length - 1))];
setInterval(console.log,1000, complement);

You need to pass a callbnack function to setInterval that is executed, and move you random access there.

setInterval(() => {
   console.log(complements[Math.floor(Math.random() * (complements.length - 1))])
}, 1000)
Sign up to request clarification or add additional context in comments.

Comments

0

Try to use setInterval like this:

setInterval(() => {
  const value = complements[Math.floor(Math.random() * (complements.length - 1))];
  console.log(value);
},1000);

Comments

0

Problem is setInterval. He call the function with the same result. Try it and check console

let x = setInterval(console.log(Math.random()),1000,);

let num = 0;
let y = setInterval(() => {
console.log(num)
num += 1
}
,1000,);

Comments

0

Rather than pass a fixed argument to console.log in each iteration (I'd actually never seen setInterval called with more than 2 parameters before and had to look up what it meant :-)), pass a function which, when called, generates a new random value and passes that to console.log:

 setInterval(() => {
    const complement = complements[Math.floor(Math.random() * (complements.length - 1)) ] ;
    console.log(complement);
 }, 1000)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.