0

I want to make a small dead chat ping function for my discord bot. The time it sends the ping should be random. I tried this code down here but the interval doesn't wait untill the "wait" is finished and repeats it unlimited times. It there maybe an alternative?

 setInterval(function() {
    var rating = Math.floor(Math.random() * 5000000) + 5000;
    setTimeout(function(){ 
        client.channels.cache.get('933372453009379338').send(`testing ${rating}`)
     }, rating);
}, 1);
  • https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep as an alternative for `setTimeout()`. – Reporter Jan 20 '22 at 13:58

1 Answers1

1

Just use setTimeout only, and let its callback initiate the next execution of that logic:

function loop() {
    var rating = Math.floor(Math.random() * 5000000) + 5000;
    setTimeout(function(){ 
        client.channels.cache.get('933372453009379338').send(`testing ${rating}`);
        loop();
    }, rating);
}

loop(); // start it
trincot
  • 317,000
  • 35
  • 244
  • 286