I have two event listeners and they are both fired on pageload depending on a video state. But if both are fired, I want the first one to stop running. How is that possible?
obj.addEventListener('suspend', () => {
// when only this is fired -> run this code
// my code
});
obj.addEventListener('play', () => {
// when this is fired too -> run this code and deactivate the first code
// my code
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You need to define a global variable and check if it is true , not to fire the first function. But there may be some runtime problems , if between running the first event , second event called , first event will not freeze and continues to run.
let shouldRun = true;
obj.addEventListener('suspend', () => {
// when only this is fired -> run this code
if(!shouldRun){
return;
}
// my code
});
obj.addEventListener('play', () => {
// when this is fired too -> run this code and deactivate the first code
shouldRun = false;
// my code
});
CodePudding user response:
I guess You can try using obj.removeEventListener('suspend') on the Call of 'play' event.
For more about removeEventListener, you can go through the official link. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
CodePudding user response:
A simple way to solve this is to remove the event handler with removeEventListener()
.
function handleSuspend() {
// when only this is fired -> run this code
// my code
}
function handlePlay() {
// when this is fired too -> run this code and deactivate the first code
obj.removeEventListener('suspend', handleSuspend);
// my code
}
obj.addEventListener('suspend', handleSuspend);
obj.addEventListener('play', handlePlay);