[英]How to use “clearInterval” in a different if statement to the “setInterval”
我已经尝试搜索其他示例,以自己解决此问题,但我对一般编码还很陌生,而且我对 java 脚本非常陌生,所以我提前为我犯的任何愚蠢错误道歉。
基本上,我正在学习 javascript,我认为一个好的交互式学习方式是制作一个 discord 机器人,这样我就可以“看到”我的努力得到回报,从而保持我的动力。 我决定一个基本的垃圾邮件机器人将是一个很好的起点,让我熟悉最基本的方面。
经过一番研究,我发现方法“ setInterval ”似乎非常适合我心目中的应用程序。 此方法将在每个给定的时间间隔执行一行代码。
所以我可以让我的机器人向 discord 频道发送垃圾邮件就好了,但我遇到的这个问题是如果我想让它停止。
client.on('message', message => { //reacting when ever the 'message' EVENT occurs (e.g. a message is sent on a text channel in discord)
console.log('A message was detected and this is my reaction');
console.log(message.author + ' also knows as ' + message.author.username + ' said:\t' + message.content); //message.author is the value of the person who sent the message, message.content is the content of the message
if(message.author.bot) {
return null //returns nothing if the message author is the bot
} else if (message.content.startsWith(`${prefix}spam`)) {
let timerId = setInterval(() => { //starts to spams the channel
message.channel.send('spamtest');
}, 1500);
} else if (message.content.startsWith(`${prefix}stop`)) {
clearInterval(timerId);
message.channel.send('condition met');
}
});
我在这里得到的错误是 timerId 没有定义。 所以我认为那是因为它是一个局部变量,现在我很难过。 我不知道还有什么可以尝试的,而且我对这么简单的事情感到非常沮丧,所以我希望这里有人可以提供帮助。
谢谢
正如Jaromanda X 在评论中所述, let
关键字在当前块 scope 中声明了一个变量,使另一个块 scope(另一个else if
块)无法访问该变量。
要解决此问题,您需要在全局 scope 中声明变量timerId
,以便所有其他块作用域都可以访问它:
let timerId; // declare timer in global scope
client.on('message', message => { //reacting when ever the 'message' EVENT occurs (e.g. a message is sent on a text channel in discord)
console.log('A message was detected and this is my reaction');
console.log(message.author + ' also knows as ' + message.author.username + ' said:\t' + message.content); //message.author is the value of the person who sent the message, message.content is the content of the message
if(message.author.bot) {
return null //returns nothing if the message author is the bot
} else if (message.content.startsWith(`${prefix}spam`)) {
timerId = setInterval(() => { //starts to spams the channel
message.channel.send('spamtest');
}, 1500);
} else if (message.content.startsWith(`${prefix}stop`)) {
clearInterval(timerId);
message.channel.send('condition met');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.