第一个setTimeout正常运行,其余失效的Discord机器人代码问题求助
问题分析与解决方案
嘿,我来帮你排查这个问题~你遇到的情况是因为三个setTimeout是同时被触发的,它们的延迟时间都是1000毫秒(1秒),所以当第一个setTimeout执行完后,另外两个也会在同一时间点触发,自然就没有间隔了。
错误原因拆解
当你的代码执行到这三个setTimeout时,它们会被同时加入到事件队列中,各自等待1秒后执行。也就是说:
- 第一个
setTimeout:当前时间 +1秒 发送i am here - 第二个
setTimeout:同样是当前时间 +1秒 发送and i hope you are fine - 第三个
setTimeout:还是当前时间 +1秒 发送what do you want me to do?
所以这三句话会在1秒后几乎同时发送,看起来就像没有间隔一样。
解决方案1:累加延迟时间
最简单的修复方式是把后面的setTimeout延迟时间依次累加,让它们按顺序触发:
bot.on('message', message=> { if(message.content === "come here") { message.channel.send('hey'); setTimeout(() => { message.channel.send('i am here'); }, 1000); setTimeout(() => { message.channel.send('and i hope you are fine'); }, 2000); // 延迟2秒 setTimeout(() => { message.channel.send('what do you want me to do?'); }, 3000); // 延迟3秒 } })
这样第一个消息在1秒后发,第二个在2秒后(比第一个晚1秒),第三个在3秒后(比第二个晚1秒),就能实现你想要的间隔效果了。
解决方案2:用async/await+Promise实现更优雅的顺序执行
如果后续有更多消息要发送,累加延迟会变得麻烦,推荐用async/await结合Promise封装一个延迟函数,代码可读性更高:
// 封装一个延迟函数 function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } bot.on('message', async message=> { // 注意这里加async if(message.content === "come here") { await message.channel.send('hey'); await delay(1000); await message.channel.send('i am here'); await delay(1000); await message.channel.send('and i hope you are fine'); await delay(1000); await message.channel.send('what do you want me to do?'); } })
这种方式每一步都会等待上一步完成并延迟1秒后,再执行下一步,逻辑更清晰,也更容易维护。
内容的提问来源于stack exchange,提问作者unclast
相关产品推荐
相关产品推荐

