0

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?

connexo
  • 53,704
  • 14
  • 91
  • 128

1 Answers1

0

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

Kaiido
  • 123,334
  • 13
  • 219
  • 285