-1

i got a part of code that should send message in discord every x second but it awaits x seconds and sends all messages at once

let amount = 5;
let interval = 3000
for (i = 0; i < amount; i++) {
  setInterval(() => {
    message.channel.send($arr[Random(0, $arr.length)]);
  }, interval);
}

I tried this outside the loop , with setTimeout() and clearInterval() or clearTimeout() it never worked

EDIT:

let amount = 5;
const interval = 300; // 3000
const tId = setInterval(() => {
  console.log(amount)
  // message.channel.send($arr[Random(0, $arr.length)]);
  if (--amount === 0) clearTimeout(tId);
}, interval);
Tiko
  • 1,241
  • 11
  • 19

2 Answers2

1

You should make a function and call it within itself in the setTimeout (instead of setInterval), and use counter instead of the for loop.
What happens in your code: all the setInterval inner code is executed at once...

Try something like this:

var counter = 0;
var amount = 5;
var interval = 3000

function msg() {
  message.channel.send($arr[Random(0, $arr.length)]);
  counter++;
  if(counter<amount) {
    setTimeout(msg, interval);
  }
)

msg();
iAmOren
  • 2,760
  • 2
  • 11
  • 23
1

You need to give the CPU a breather

let amount = 5;
const interval = 300; // 3000
const tId = setInterval(() => {
  console.log(amount)
  // message.channel.send($arr[Random(0, $arr.length)]);
  if (--amount === 0) clearTimeout(tId);
}, interval);
mplungjan
  • 169,008
  • 28
  • 173
  • 236