JavaScript中的异步事件处理 [英] Asynchronous event handling in JavaScript
问题描述
我在防止在代码中进行双重(多个) eventListener
处理时遇到问题:
I have an issue with preventing double (multiple) eventListener
handling in code:
var locked;
button.addEventListener("click", function() {
if (locked) return;
locked = true;
calculateSomethingHeavy();
locked = false;
}
第二次立即单击按钮会触发另一个事件,尽管 locked == true
.像 button.disabled = true
或 setTimeout(function(){locked = true;},0)
之类的东西都没有效果,因为(我猜)第二个调用被堆叠了并且会只有先处理完后才能调用.我想我缺少一些异步事件处理的完整技术.如何在纯js中做到这一点?
Second immediate button click triggers another event, despite locked == true
. Things like button.disabled = true
or setTimeout(function() {locked = true;}, 0)
have no effect because (I guess) second call is stacked and will be invoked only after first is fully handled. I think I'm missing some whole technology of asynchronous event handling. How to do this in pure js?
推荐答案
此处的正确答案取决于 calculateSomethingHeavy
的定义.大概它基于问题标题是异步的,但是可以使用回调,事件,promise或async/await来实现.
The correct answer here depends on the definition of calculateSomethingHeavy
. Presumably it's asynchronous based on the question title, but that could be implemented using callbacks, or events, or promises or async/await.
不管其中的哪一个在起作用,您需要做的是确保直到 calculateSomethingHeavy
locked 设置为 false
.>完成.每种情况下看起来都可能如下所示……
Regardless of which of those is at play here, what you need to do is ensure that locked
is not set to false
until after calculateSomethingHeavy
has finished.
That might look like the following in each case...
var locked;
button.addEventListener("click", function() {
if (locked) return;
locked = true;
calculateSomethingHeavy(() => {
locked = false;
});
});
事件
var locked;
button.addEventListener("click", function() {
if (locked) return;
locked = true;
calculateSomethingHeavy().on('finish', () => {
locked = false;
});
});
承诺
var locked;
button.addEventListener("click", function() {
if (locked) return;
locked = true;
calculateSomethingHeavy()
.then(() => {
locked = false;
});
});
异步/等待
var locked;
button.addEventListener("click", function() {
if (locked) return;
locked = true;
await calculateSomethingHeavy();
locked = false;
});
这篇关于JavaScript中的异步事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!