4

Consider the following React component. My query is not limited to React. It is a Javascript question:

function MyTest(){
  const result = () =>{
      console.log("Time to play");
      setTimeout (() =>{
          console.log("async")
      },500);
  };
    useEffect(()=>{
        document.getElementById('id-1').click();
        console.log("When?");
    })
    return (
        <button id="id-1" onClick={result}>Click me</button>
    )
}

The output of the above code is:

Time to play
When?
async

But I am confused with the event handler. What I know is: browser event handlers behave like other asynchronous notifications. They are scheduled when the event occurs but must wait for other scripts that are running to finish before they get a chance to run. If the above is correct, I would expect the following output:

When?
Time to play
async

because the execution stack is not empty(console.log("When?") lies inside it) as for the event handler to run. What is wrong in the above syllogism?

P.S. To get the above more confusing have a look at Asynchronous or Synchronous calling of event handlers in javascript

Unknown developer
  • 5,414
  • 13
  • 52
  • 100

2 Answers2

0

Looking at this link https://w3c.github.io/uievents/#sync-async

I see this:

Events may be dispatched either synchronously or asynchronously.

Events which are synchronous (sync events) are treated as if they are in a virtual queue in a first-in-first-out model, ordered by sequence of temporal occurrence with respect to other events, to changes in the DOM, and to user interaction. Each event in this virtual queue is delayed until the previous event has completed its propagation behavior, or been canceled. Some sync events are driven by a specific device or process, such as mouse button events. These events are governed by the event order algorithms defined for that set of events, and user agents will dispatch these events in the defined order.

So I guess this assumption isn't always the case:

browser event handlers behave like other asynchronous notifications.

And explains why you see the output you do.

Travis James
  • 1,879
  • 9
  • 22
0

@Dennis Vash 's comment explains everything.

document.getElementById('id-1').click();

does not create a browser event. As simple as that.

Unknown developer
  • 5,414
  • 13
  • 52
  • 100