繁体   English   中英

如何防止事件监听器 function 被同时触发多次

[英]how to prevent a event listener function to be triggered several times at the same time

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

根据您的需要,此问题有多种解决方案。

  1. 事件发生后立即取消注册事件侦听器。 在大多数库中,您可以通过使用once()方法而不是“on()”注册事件来轻松实现
  2. 使用debounce()将一定时间内触发的所有事件聚合为一个。

类似lodash的大部分JS库中都存在相同或相似的方法。

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

Lodash 有一个 package 可以单独导入

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM