I have the following question about micro and macro tasks running in Google Chrome. See the next example (The following code was proposed by Jake Archibald):
// 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);
inner.click();
If you run the following code, the order of logs is:
click
click
promise
mutate
promise
timeout
timeout
There are two questions about what is happening here that I don't understand, for both I have a vague idea.
- Why click is print twice if inner.click() is called once? I think that it is because click inner makes click outer too, but I am not sure.
- Why mutate changes only once? It makes sense to me because in the second iteration it is already mutated so it doesn't trigger the callback.
I am not sure in none of them.
Any ideas? Thanks, Manuel