1

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.

Michi_Ki
  • 11
  • 3

1 Answers1

0

I am not a JS Guru and I didn't know why you asked, but your first approach is almost correct. Remove last line of showAlert where you add new event listener. this solution works fine, tested on iphone 10

function test() {
    window.removeEventListener('orientationchange', test);
    alert('orientation change')
}

window.addEventListener('orientationchange', test);
  • Thank you for your fast response. Maybe I should have been more precise with my wording. In fact I do want the event to be triggered again. Just not while the alert is shown. That's why I readded the eventlistener at the end of the function. – Michi_Ki Feb 23 '21 at 15:39