首页 > 解决方案 > 如何防止一个事件监听函数同时被触发多次

问题描述

我的问题很简单,我正在使用 discord js,并在我的代码中添加了这个事件监听器。当用户在频道中发送特定消息时会触发此侦听器功能。但是,如果 2 个用户同时发送此特定消息,则侦听器功能会同时触发两次。我怎样才能防止这种情况?

标签: javascriptnode.jseventsdiscorddiscord.js

解决方案


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

Lodash 有一个可以单独导入的包

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)


推荐阅读