Order of execution of functions bound to an event in Javascript

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:

        This example uses the addEventListener() method to attach a click event to a button.
    <p id="demo"></p>
    <button id = "myBtn">Try it</button>
        function mySecondClick(){
            document.getElementById("demo").innerHTML ="Hello World!";
        function myClick(){
            alert("Hello World!");

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 is easier to see that @kevcomedia is correct, when you look at a modified version of your code (using console.log statements instead of alerts. Notice, the console display order is 3rd, 2nd, 1st, because that is the order they appear as attachments to the button.

  <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>
    document.getElementById("myBtn").addEventListener("click", myThirdClick);    
    document.getElementById("myBtn").addEventListener("click", mySecondClick);
    document.getElementById("myBtn").addEventListener("click", myClick);
    function myClick() {
    function mySecondClick() {
    function myThirdClick() {

The above produces the following after each click of the button:


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.

Yes, I tried it on Firefox as well, the result is different.Thanks a lot!