Search code examples
javascriptsettimeoutsetinterval

setInterval/setTimeout problem getting messages at once


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);

Solution

  • 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);