如何在异步设置超时中获得剩余时间?
我无法获取有关冷却剩余时间的信息。具体来说,当用户运行命令时,超时开始以防止任何其他输入。
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
const doStuffAsync = async () => {
await setAsyncTimeout(() => {
isReady = true;
console.log("Cooldown finished.");
}, 60000);};
twitch.on('message', (channel, tags, message, self) => {
if (isReady){
isReady = false;
console.log("running command");
doStuffAsync();
}
else if (!isReady){
console.log("Not Ready Message should come up here");
} return;
});
我试图让机器人在剩余的冷却时间内回复另一个用户,但我无法这样做。任何人都可以指导我走上正确的道路吗?
回答
不要使用setTimeout- 只需跟踪上次完成此操作的时间。
let lastInvocationTime = 0;
twitch.on("message", (channel, tags, message, self) => {
const now = +new Date(); // get current clock time as milliseconds
const timeSinceLastInvocation = now - lastInvocationTime;
if (timeSinceLastInvocation > 60000) {
console.log("running command");
lastInvocationTime = now;
} else {
console.log(`Sorry, only ${timeSinceLastInvocation / 1000} seconds have passed since the last run.`);
}
});