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