Javascript 是否可以在设定的超时范围内清除超时或停止超时?

Javascript 是否可以在设定的超时范围内清除超时或停止超时?,javascript,Javascript,基本上,我有一个设定的超时,我想让它,如果在超时期间发生了什么事情,我可以结束它。这是代码 let QandA = db.get(`QandA`) QandA.forEach((element, index) => { async function quiz(message, element){ let split = element.split('|') message

基本上,我有一个设定的超时,我想让它,如果在超时期间发生了什么事情,我可以结束它。这是代码

        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')
                }
            }
        })
让QandA=db.get(`QandA`)
QandA.forEach((元素,索引)=>{
异步函数测验(消息、元素){
设split=element.split(“|”)
message.channel.send(`**${split[0]}**`)
message.channel.awaitMessages(m=>m.content.includes(split[1]),{max:2,time:5000}),然后(collected=>{
if(collected.first().author.bot){
返回
}
if(collected.first().content==split[1]){
message.channel.send(`恭喜你做对了')
var ttttt=true
ttt()
}
})
}
变量计时器=设置超时(()=>{
测验(信息、元素)
},5000*指数);
异步函数ttt(){
中频(定时器){
清除超时(计时器)
console.log('Done')
}
}
})
async function quick'可以上移到'QandA.forEach'之上` 您只需要定义该函数一次,而不需要在循环中重复定义

你的代码看起来像是你的5秒延迟来自waitmessages函数? 我这样说是因为您正在将5000ms延迟参数传递给该函数。为什么需要传递它,除非该函数实现延迟?假定
等待消息
返回承诺,因为您正在使用
。然后

因此,您的“.setTimeout”只是延迟每个问题的开始,而不是它们的结束 看起来您是在一开始就设置每个问题的开始时间,方法是创建一系列具有不同延迟的设置超时

因此,我的结论是,如果用户希望提前退出整个测验,您希望了解如何
取消设置超时,以供以后的问题使用

保留一个设置超时的数组 当你想关闭测验时,你可以用这样的循环来取消它们

    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));

您不必担心清除设置超时。因为这是一次性的行动。您可以从回调函数返回以获得所需的结果。如果split[1]等于collected,我想确定它。首先()然后移动到数组中的下一部分,这是可能的吗?问题是,当您在quick函数中时,setTimeout回调已经执行。因此,在测试函数完成后,它将移动到下一个数组项。你不必清除超时时间或其他任何事情。问题是我希望它早点结束。我想早点结束。对不起,你能澄清一下吗?1.我对你的问题的每一种解释都是对的吗。提前结束什么?一个单独的问题,还是整个测验?一个单独的问题,假设某人正确回答了一个问题,我希望它立即转到下一个问题