In Javascript, if an event is triggered and the corresponding callback is added to the message queue of the Javascript engine event loop. Is it possible to remove it from the queue through Javascript code?
Note that the events are called in high frequency, so it may be added to the event queue before any Javascript code is executed. I didn't see a description saying that removeEventListener actually goes through the message queue and remove corresponding events; want to double check if removeEventListener actually does that and such function is implemented the same way across all Javascript engines.
Standard Javascript does not offer any direct access to the event queue. You can listen for events (often with .addEventListener() or by registering callbacks and, when it is their turn, that event will fire and your callback will get called. Or, some listeners can be removed with .removeEventListener() or by canceling a specific operation (like clearTimeout()), but, there is no direct access to managing the event queue.
You would likely have to somehow have native code inside the VM in order to do that and how to do it would be non-standard and specific to a particular Javascript VM.
If you really just want to be able to easily prevent a callback from getting called more than once, then you can create a little stub that will do that for you.
function callOnce(fn) {
var called = false;
return function() {
if (!called) {
called = true;
return fn.apply(this, arguments);
}
}
}
// create a callOnce function stub for myFunction
var cb = callOnce(myFunction);
obj1.addEventListener("click", cb);
obj2.addEventListener("click", cb);
obj3.addEventListener("click", cb);
myFunction will only ever get called once whenever the first event calls it. After that, it will be blocked by the callOnce stub that was created when cb was defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With