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;
}
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?
calculateSomethingHeavyheavy or asynchronous (or both)? Those are very distinct conceptscalculateSomethingHeavyis meant to be asynchronous and you needlockedto be set to false after it completes, then you need to return a Promise fromcalculateSomethingHeavyand set locked to false in its success handler. As written, this is synchronous code, so locked will be set to false immediately aftercalculateSomethingHeavyis called.calculateSomethingHeavyis a bit tricky - the function fills a big canvas with pixels and after its first call it timeouts itself 99 more times to give some time for refreshing progress bars on the page (so each function call does 1% of all calculations). But the thing is,eventListenerbehaviour doesn't depend on existence of those timeouts, so I put simplified version here (I hope solution also doesn' depend on that)