I have known that event handlers are always called int the order in which they are registered.
So I wrote some code to test the order, although, the result is frustrating.
here is my code:
…
<body>
<p>
This example uses the addEventListener() method to attach a click event to a button.
</p>
<p id="demo"></p>
<button id = "myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click",mySecondClick);
document.getElementById("myBtn").addEventListener("click",myClick);
function mySecondClick(){
document.getElementById("demo").innerHTML ="Hello World!";
}
function myClick(){
alert("Hello World!");
}
</script>
</body>
…
I found that the function myClick was executed firstly, it should be executed later.
I am confused right now, please help me!
The myClick function is actually executed after mySecondClick. If you looked at the page, the <p> has already updated its text when the alert box shows up. If you switched the order of adding the event listeners, the alert would pop up first before the <p> updates.
Please check these pictures.
The first one is a screenshot after I click the button, the alert window is popped up before the p element updates.
The second one is a screenshot after I click the OK button, the p element doesn’t update until then.
The function execution order does not meet expections.
I don’t know if the cookies will affect the function execution order, because I have tried different functions registration order.
It looks like it depends on the browser when alerts are involved. I tried it on Chrome and the alert pop up always appears first. You can see the <p> updating on Firefox before the alert pop up.