I'm currently experiencing a problem in Javascript when I try to prevent an eventhandler from being called multiple times simultaneously. I know that Javascript is single threaded and my question therefore seems strange.
Here is the code that is loaded inside the head of my html file via <script src="main.js"></script>
:
function showAlert ( ) {
window.removeEventListener ( 'orientationchange' , showAlert );
alert ( 'alert' );
// code execution doesn't seem to stop here while the alert is open
window.addEventListener ( 'orientationchange' , showAlert );
}
function onLoad ( ) {
document.removeEventListener ( 'DOMContentLoaded' , onLoad );
window.addEventListener ( 'orientationchange' , showAlert );
}
document.addEventListener ( 'DOMContentLoaded' , onLoad );
When I turn my phone the alert is shown. Unfortunately, when I don't close the alert and turn my phone again, a second alert is shown. This should not happen because I already removed the eventlistener before showing the first alert.
I've also tried to prevent this behavior via a global variable, but it didn't work either:
var alertIsShown = false;
function showAlert ( ) {
if ( alertIsShown == false ) {
alertIsShown = true;
alert ( 'alert' );
// code execution doesn't stop here
alertIsShown = false;
}
//alertIsShown = false; // doesn't matter if I put the alert here
}
function onLoad ( ) {
document.removeEventListener ( 'DOMContentLoaded' , onLoad );
window.addEventListener ( 'orientationchange' , showAlert );
}
document.addEventListener ( 'DOMContentLoaded' , onLoad );
I've also checked if the DOMContentLoaded event was somehow triggered multiple times, but it wasn't the case.
This question here seems to be similiar, but I get an alert no matter how long I wait before turning my phone.
Is there any Javascript Guru out there that can help me out?
Update 01: I found out that despite what the majority on the internet says, a pause of the code execution while an alert message is shown is defined as optional in the official specs. Unfortunately, switching to confirm didn't solve my problem either. When the phone is rotate while the message box is showing, another message box is shown.