在循环中生成随机数,并使循环等待该随机数



我想为我的discord机器人制作一个小的死聊ping功能。它发送ping的时间应该是随机的。我在这里尝试了这个代码,但间隔不会等到";等待";完成并无限次重复。也许还有其他选择?

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

只需使用setTimeout,并让其回调启动该逻辑的下一次执行:

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

最新更新