client.on('message', msg => {
if (msg.content === 'startspam') {
function spam(){
msg.channel.send('a')
}
setInterval(spam, 2500)
}
});
client.on('message', msg => {
if (msg.content === 'stopspam') {
}
});
如何停止函数垃圾邮件(对不起,我是JavaScript的新手,我正在努力学习基础知识)
可以对setInterval返回的数字使用clearInterval函数来停止间隔。我在下面添加了一些代码来展示它是如何工作的。
var interval = setInterval(someFuntion, 200);
clearInterval(interval);
Try clearInterval
const print = () => console.log('alive');
const intervalId = setInterval(print, 1000);
const stopInterval = () => clearInterval(intervalId);
<button onclick='stopInterval()'>Stop</button>
我还会移动语句
function spam(){
msg.channel.send('a')
}
在当前代码之外或更改为匿名函数:
tId = setInterval(function() { msg.channel.send('a') }, 2500)
并将tId作为全局变量,这样您可以通过clearInterval(tId)
来停止它
如果我理解正确,您正试图停止在setInterval
中调用的span函数。这可以用clearInterval
来完成。
试试这个:
client.on('message', msg => {
var interval;
function spam(){
msg.channel.send('a');
}
function start() {
interval = setInterval(spam, 2500);
}
function stop() {
clearInterval(interval);
}
if (msg.content === 'startspam') {
start();
}
if (msg.content === 'stopspam') {
stop();
}
});
首先Java和javascript是不一样的…
对于你的问题-
你可以使用这个clearInterval()
此函数接收您想要停止的间隔的id。和interval函数返回一个唯一的数字,所以它可以用作ID..
你可以这样做:
var intervalID = '';
function startInterVal() {
intervalID = setInterval(() => {
console.log('Hello')
}, 1000)
}
function stopInterval() {
clearInterval(intervalID);
}
<button onClick="startInterVal()">Start</button>
<button onClick="stopInterval()">Stop</button>
希望我能帮到你。