如何让事件监听器暂时暂停?

时间:2021-05-24 16:14:54

标签: javascript node.js discord.js

client.on('message', message => {
  if (message.content.startsWith("ping")) {
    message.channel.send('Pong!');
  }
});

如何添加冷却时间(不是特定于用户的),以便一旦触发此事件,它会休眠 60 秒?

2 个答案:

答案 0 :(得分:0)

执行操作时,将函数外部的变量设置为 true

如果函数为 true,则中止函数。

使用 setTimeout 将其重新设置为 false


let cooldown = false;

client.on('message', message => {
  if (message.content.startsWith("ping")) {
    if (cooldown) return;
    cooldown = true;
    setTimeout(() => { cooldown = false; }, 60000);
    message.channel.send('Pong!');
  }
});

答案 1 :(得分:0)

您应该尝试去抖动。在这种情况下可能看起来有点矫枉过正,但这个概念绝对值得学习,您可以在代码库中一遍又一遍地使用这种东西,而不必在每个处理程序的范围之外声明单独的超时变量。

以下实现改编自 https://davidwalsh.name/javascript-debounce-function

function debounce(func, wait, immediate) {
    let timeout;

    return function(...args) {
        const context = this;
        const later = () => {
            timeout = null;
            if (!immediate)
                func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);

        if (callNow)
            func.apply(context, args);
    };
};

你可以像这样使用

client.on("message", debounce(message => {...}, 60 * 1000, true));

注意,debounce 返回 function 而不是 () => {...} 很重要,因为 func 可能期望有意义的 this 上下文,这只能是绑定 function 函数。