我正在尝试在js中创建一个玩笑机器人,该机器人在延迟后会发送紧急通知。
这是我正在使用的代码。它只会向我发送紧急信号atm。我已经删除了一些代码,因为它重复了该问题。
var delayInMilliseconds = 1500;
function poolJoke() {
const rand = Math.floor(Math.random() * 7) + 1;
if (rand === 1) {
bot.postMessageToChannel(
'bots',
'What does bread loaves say when they greet each other?',
setTimeout(function() {
bot.postMessageToChannel('bots',
'Gluten tag.')
}, delayInMilliseconds),
params
);
}
}
嗨,您需要添加一个局部变量和清除时间,请尝试以下代码
function poolJoke(val) {
var timer;
const rand = val;
if (rand == 1) {
window.clearTimeout(timer);
console.log('What does bread loaves say when they greet each other?');
timer = setTimeout(function () {
console.log('bots', 'Gluten tag.' + timer)
}, 5000);
}
}
请尝试我测试过的此解决方案,然后正常运行:
bot.on("start", function() {
bot.postMessageToChannel(channel, "Hello world!");
console.log("Hello world!");
setTimeout(() => {
bot.postMessageToChannel(channel,'after 5000 ms.')
}, 5000)
});