back to catalog
MutationObserver microtask substack
观察MutationObserver中的microtask substack的event loop执行顺序

      const dom = document.getElementById('container')

      var config = { attributes: true, childList: true, subtree: true };
  
      var callback = function(mutationsList, observer) {
          for(var mutation of mutationsList) {
              if (mutation.type == 'childList') {
                  console.log('MutationObserver event callback')
                  setTimeout(() => {
                    console.log('setTimeout callback in MutationObserver')
                  })
                  Promise.resolve().then(() => {
                    console.log('promise callback in MutationObserver')
                  })
              }
              else if (mutation.type == 'attributes') {
                  console.log('The ' + mutation.attributeName + ' attribute was modified.');
              }
          }
      };
  
      var observer = new MutationObserver(callback);
  
      observer.observe(dom, config);
  
      setTimeout(() => {
        console.log('setTimeout callback')
      })
      
      Promise.resolve().then(() => {
        console.log('promise callback before MutationObserver')
      })
  
      console.log('before trigger MutationObserver')
      const span = document.createElement('span')
      span.textContent = 'hello'
      dom.appendChild(span)
  
      Promise.resolve().then(() => {
        console.log('promise callback after MutationObserver')
      })
        
      setTimeout(() => {
        console.log('disconnect')
        observer.disconnect();
      })