基本上,我有一个设置的超时,我想让它在超时期间发生什么事情,我可以结束它。下面是代码。
let QandA = db.get(`QandA`)
QandA.forEach((element, index) => {
async function quiz(message, element){
let split = element.split('|')
message.channel.send(`**${split[0]}**`)
message.channel.awaitMessages(m => m.content.includes(split[1]), { max: 2, time: 5000 }).then(collected => {
if (collected.first().author.bot) {
return
}
if (collected.first().content === split[1]) {
message.channel.send(`Congratulations <@${collected.first().author.id}> You got it right`)
var ttttt = true
ttt()
}
})
}
var timer = setTimeout(() => {
quiz(message, element)
}, 5000 * index);
async function ttt(){
if(timer){
clearTimeout(timer)
console.log('Done')
}
}
})发布于 2020-10-28 00:03:54
可以将async function quiz向上移动到QandA.forEach上方
您只需定义该函数一次,而不是在循环中重复定义。
您的代码看起来像是来自awaitMessages函数内部的5秒延迟?
我之所以这样说,是因为您正在向该函数传递5000 ms的延迟参数。为什么需要传递它,除非该函数实现了延迟?由于您使用的是.then,因此awaitMessages可能会返回一个promise。
因此,你的.setTimeout仅仅是延迟每个问题的开始,而不是它们的结束
看起来你在一开始就设置了每个问题的开始时间,通过创建一系列具有不同延迟的setTimeouts。
因此,我得出的结论是,如果用户想要提前退出整个测验,那么您正在寻找如何为稍后的问题cancel setTimeout?
保留setTimeouts的数组
当您想要关闭测验时,您可以使用如下循环将其全部取消。
const QandA = db.get(`QandA`)
const questionStartTimers = []
// ... other stuff here
var questionStartTimers[index] = setTimeout(() => {
quiz(message, element)
}, 5000 * index);
// Then when you want to "kill" all future questions that are waiting to be asked:
questionStartTimers.forEach(timer=> clearTimeout(timer));https://stackoverflow.com/questions/64556757
复制相似问题