在 setInterval 运行时使用 clearInterval

Using clearInterval while setInterval runs

对使用 JS 相当陌生,并试图创建一个采用 JSON 数组的 Discord 机器人,从相关键中随机选择 1 个值,并每 24 小时自动输出一次(基本上是引号当天的机器人)。

我目前正在使用 setInterval 来执行此操作,但是,在 运行 期间我无法 clearInterval,让我 ctrl + C电源外壳。

client.on('message', function(message) {

if(message.author.bot) return;

if(message.content.indexOf(config.prefix) !== 0) return;

const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();

if (command === "qotd") 
{ 
const intervalSet = args.join(" ")
message.channel.send(randomQuestion())
    var interval = setInterval (function () 
    {
        //randomQuestion() is the function that returns the randomly selected value
        //message.channel.send(randomQuestion()) is there twice so it runs once 
        //before the timer starts (otherwise it'll take x time to output once
        message.channel.send(randomQuestion())
        .catch(console.error) // add error handling here
        return interval;
    }, intervalSet); 

}

if (command === "stopqotd")
{
    clearInterval(interval);
}
});

我试过将另一个带有 clearInterval(interval) 的命令放在同一个 client.on() 和单独的命令中,两者都不会阻止它。

它需要停止的唯一原因是 add/remove 引用。不然只能运行没完没了

有什么建议吗?

您的 interval 变量不在您尝试调用的位置范围内 clearInterval()

要修复,将其移动到更高的范围:

let interval;

if (command === 'qotd') { 
  // ...
  interval = setInterval(function() {/*...*/}, intervalSet);
}

if (command === 'stopqotd') {
  clearInterval(interval);
}

这仍然会让您处于这样一种情况:如果您收到多个 qotd 命令,您将有多个间隔 运行,其中只有最后一个会被 stopqotd命令。

解决此问题的一种方法是在清除 interval 后将其设置为 undefined,并在收到 qotd 命令时测试该值。

let interval;

if (command === 'qotd') { 
  // ...
  if (!interval) {
    interval = setInterval(function() {/*...*/}, intervalSet);
  } else {
    message.channel.send('QOTD already running');
  }
}

if (command === 'stopqotd') {
  clearInterval(interval);
  interval = undefined;
}