Search code examples
javascriptevent-looporder-of-execution

Execution order with nested event handlers


Check this simple example:

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>

This outputs (as I expected):

foo listener executed
click listener executed
end reached

Can I rely on this execution order?


Solution

  • Yes, EventTarget.dispatchEvent() dispatches the event synchronously.