Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is triggering event listeners using ".click()" asynchronous?

I have the following code (where there is a <button id="7"> in my HTML):

(function() {
  'use strict';
  document.getElementById(7).addEventListener("click", function(){
    console.log('clicked');
  })
  console.log('before');
  document.getElementById(7).click();
  console.log('after')
}());

When this runs in the Firefox 41 console, I would have expected

before
after
clicked

because the code would run synchronously, and then respond to the click event on the event queue once it had completed the script. Instead I get

before
clicked
after

This suggests the event is being handled synchronously?

like image 796
Dan Avatar asked Nov 10 '15 01:11

Dan


People also ask

Are event listeners asynchronous?

Event handlers are really a form of asynchronous programming: you provide a function (the event handler) that will be called, not right away, but whenever the event happens.

Are event listeners synchronous?

That's correct. All event handlers are fired synchronously and in order of binding.

Are event handlers Asynchronous JavaScript?

Because these events happen at unpredictable times and in an unpredictable order, we say that the handling of the events, and therefore the invocation of their handling functions, is asynchronous.

How do you trigger an event on click?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.


1 Answers

Yes, the click method does synchronously run the activation steps which includes immediately firing (creating and dispatching) the event. It is not put in the event loop queue.

like image 182
Bergi Avatar answered Nov 09 '22 08:11

Bergi