Order of execution of event listeners

Say you attach several listeners to an event, for example you want a few things to happen on page load. What is the order of execution of the different listeners? You'd think that the listener attached first will execute first, followed by the second and so on… Well, yes, in FF, Opera, Safari on Windows, but not in IE.

The test

  var i = 1, ol = document.getElementById('result');

  for (i; i <= 10; i++) {
      YAHOO.util.Event.addListener(window,'load',
        function(num){
            return function(){
                ol.innerHTML += '<li>' + num + '</li>';
            }
        }(i)
      );
  }

Result in FF, O, Safari

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Result in IE

  1. 1
  2. 2
  3. 4
  4. 6
  5. 8
  6. 10
  7. 9
  8. 7
  9. 5
  10. 3

Observation

Here you can try it out yourself

Try in IE. Reload. Reload again. Notice something? The order is not random. Always starts 1, 2, then goes through all even numbers until 10 then backwards - 9, 7, 5, 3 - all odd numbers.

Try with a bigger loop - still the same thing. Hmm, interesting… Maybe not something you'd like to rely on, but still…


Post this entry to: » del.icio.us  » Digg  » Furl  » Newsvine  » reddit  » Y!

Somewhat related posts

3 Responses to “Order of execution of event listeners”

  1. Mrasnika’s Lair » IE нормален браузър ... да, да ! Says:

    […] Order of execution of event listeners http://www.phpied.com/order-of-execution-of-…-listeners/ […]

  2. steve Says:

    Correction:

    This appears to be a feature/bug of the YAHOO.util.event code.

    If you roll your own addEventListenter function… that (for IE), calls attachEvent(…) you'll find that they are added in the "correct" order.

    Cheers,
    Steve

  3. Stoyan Says:

    Really? Interesting…

Leave a Reply