嵌套事件处理程序的执行顺序

Execution order with nested event handlers

检查这个简单的例子:

function doit() {
  const button = document.querySelector('button');

  button.addEventListener('click', (e) => {
    dispatchFoo();
    console.log('click listener executed');
  })
  
  document.addEventListener('foo', handleFoo);

  button.click();

  console.log('end reached')
}

function handleFoo() {
  console.log('foo listener executed');
}

function dispatchFoo() {
  const event = new CustomEvent('foo');
  document.dispatchEvent(event);
}

console.clear();
doit();
<button>button</button>

这输出(如我所料):

foo listener executed
click listener executed
end reached

我可以依赖这个执行顺序吗?

是,EventTarget.dispatchEvent() 同步调度事件。