javascript - 如何防止一个事件监听函数同时被触发多次
问题描述
我的问题很简单,我正在使用 discord js,并在我的代码中添加了这个事件监听器。当用户在频道中发送特定消息时会触发此侦听器功能。但是,如果 2 个用户同时发送此特定消息,则侦听器功能会同时触发两次。我怎样才能防止这种情况?
解决方案
如果您乐于忽略通过的第二条消息,您可以看看用debouncing包装您的函数,这将导致它仅在短时间连续调用时触发一次。
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)
推荐阅读
- batch-file - Windows cmd (.bat) 中的嵌套运算符
- java-8 - Java8 Stream Collectors - 根据值的总和拆分列表
- python-3.x - 对 Pandas 数据框进行分组并根据条件进行验证
- java - Spring Boot 应用程序创建两个数据库行
- ruby - 比较哈希(减法)的元素 RUBY
- laravel-5 - vue router.push : TypeError: onComplete 不是函数
- java - 默认更改日历日期
- javascript - AngularJS 隔离指令监视所有双向数据绑定的变化
- wso2 - WSO2 API 管理器启动时出现“无法添加订阅”错误
- php - php:嵌套类结构的属性继承