如何防止事件监听器功能一次被触发多次

时间:2020-04-21 22:38:55

标签: javascript node.js events discord discord.js

我的问题很容易,我正在使用Discord js,并且在我的代码中包含此事件侦听器。 当用户在通道中发送特定消息时,将触发此侦听器功能。但是,如果2个用户同时发送此特定消息,则侦听器功能将同时触发两次。我该如何预防呢?

2 个答案:

答案 0 :(得分:1)

根据您的需求,有多种解决方案。

  1. 偶数到来后立即注销事件监听器。在大多数库中,您可以使用once()方法而不是“ on()”注册事件来轻松实现
  2. 使用debounce()将在一定时间内触发的所有事件汇总为一个。

大多数与dash相似的JS库中存在相同或相似的方法。

答案 1 :(得分:1)

如果您乐于忽略通过的第二条消息,可以看看用debouncing包装函数,这将使其仅在短时间连续调用后才触发一次。

Lodash has a package for this that can be imported individually

import { myFunc } from 'somewhere';
import { debounce } from 'somewhereElse';

const DEBOUNCE_DELAY_MS = 500;
const myDebouncedFunc = debounce(myFunc, DEBOUNCE_DELAY_MS);

// Call myDebouncedFunc twice immediately after each other, the 
// debouncing will result in the function only getting called max once 
// every 500ms;
myDebouncedFunc();
myDebouncedFunc();

否则,如果需要同时处理两条消息,那么就需要诸如队列之类的东西来处理这些事件。然后您可以例如间隔处理这些消息。

// Some lexically available scope
const myQueue = [];

// Event handler
const myHandler = (msg) => {
  myQueue.push(msg);
}

// Interval processing
setInterval(() => {
  if (myQueue.length > 0) {
    const msgToProcess = myQueue.shift();
    processMessage(msgToProcess);
  }
}, 500)