From Jake Archibald's blog
Fiddle (Click on Hey): https://jsfiddle.net/1rpzycLf/
HTML:
<div class="outer">
<div class="inner"></div>
</div>
JS:
// Let's get hold of those elements
var outer = document.querySelector('.outer');
var inner = document.querySelector('.inner');
// Let's listen for attribute changes on the
// outer element
new MutationObserver(function() {
console.log('mutate');
}).observe(outer, {
attributes: true
});
// Here's a click listener…
function onClick() {
console.log('click');
setTimeout(function() {
console.log('timeout');
}, 0);
Promise.resolve().then(function() {
console.log('promise');
});
outer.setAttribute('data-random', Math.random());
}
// …which we'll attach to both elements
inner.addEventListener('click', onClick);
outer.addEventListener('click', onClick);
When running this piece for the inner div the results I get are
click
mutate
click
mutate
promise
promise
timeout
timeout
and I am struggling to see how this is the case. The Execution should be
- First Handler (Macrotask)
- Process All Microtasks
- Second Handler (Macrotask)
- Process All Microtasks
- SetTimeout (Macrotask)
- SetTimeout (Macrotask)
With this in mind, I am expecting the log to output instead:
click
promise
mutate
click
promise
mutate
timeout
timeout
Not sure why promises are being executed only after two of the click's event handler has been processed. The very first promise should ideally execute after the first mutate but we can see that it is clearly not the case. Anyone know why? (Using firefox 54.0)