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
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Result in IE
- 1
- 2
- 4
- 6
- 8
- 10
- 9
- 7
- 5
- 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...
This entry was posted on Tuesday, August 14th, 2007 and is filed under IE, JavaScript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

August 14th, 2007 at 4:40 am
[...] Order of execution of event listeners http://www.phpied.com/order-of-execution-of-…-listeners/ [...]
August 17th, 2007 at 8:07 am
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
August 17th, 2007 at 3:31 pm
Really? Interesting…
February 1st, 2012 at 12:39 pm
best los angeles real estate|los angeles homes for sale|los angeles real estate|los angeles real estate listings|real estate listings los angeles|toluca lake|toluca lake real estate|valley village|valley village ca|los angeles realtor|Burbank Real Es…
[...]Order of execution of event listeners / Stoyan’s phpied.com[...]…
February 2nd, 2012 at 1:03 pm
โทรศัพท์มือ2…
[...]Order of execution of event listeners / Stoyan’s phpied.com[...]…
February 7th, 2012 at 9:21 am
моторно масло, масло, филтри, минерално масло…
[...]Order of execution of event listeners / Stoyan’s phpied.com[...]…
July 5th, 2012 at 10:44 am
Hi! I’ve faced with this problem. Has a bug already been posted into yui2 tracker ? I can’t find it.