我的问题很容易,我正在使用Discord js,并且在我的代码中包含此事件侦听器。 当用户在通道中发送特定消息时,将触发此侦听器功能。但是,如果2个用户同时发送此特定消息,则侦听器功能将同时触发两次。我该如何预防呢?
答案 0 :(得分:1)
根据您的需求,有多种解决方案。
大多数与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)