简体   繁体   中英

Why javascript event handler is performing differently in different browser?

I am new to javascript and I am curious about a piece of code and why it is behaving differently in different browsers. This is the piece of code that I have.

function waitThreeSeconds() {
    var ms = 3000 + new Date().getTime();
    while(new Date() < ms) {}
    console.log('Finished function!')
}

function clickHandler() {
    console.log('Clicked event!')
}

document.addEventListener('click', clickHandler)

waitThreeSeconds();
console.log('Finished execution!')

As of now, I know that javascript is synchronous and single-threaded. Whenever some sort of events occur javascript puts it in the event queue and waits for the execution stack to be empty. Once the execution stack is empty then it looks into the event queue and processes the events one after another. Even after finishing all the event processing javascript still looks in the event queue for further events to appear.

Keeping this in mind, if I run this code and don't click in the window during the three seconds of delay, the output is

Finished function!
Finished execution!

and after the code executed if I clicked in the window, depending on the number of times I clicked the output becomes,

Finished function!
Finished execution!
Clicked event!
Clicked event!
...
...

Now, this is what I was expecting.

How ever, if I run the code and click in the window during the three seconds of delay, depending on the number of times I clicked the output that I expect is

Finished function!
Finished execution!
Clicked event!
Clicked event!
...
...

and it is happing for Google Chrome. However, if I do the same thing for Brave browser the output becomes

Finished function!
Finished execution!

Though I have clicked the window the output seems to look like I never clicked the window which is confusing for me.

However, after completion of execution, the code works the same way as it should be in both the browsers.

Can anybody help me to understand this behavior?

I just tried to run the code in different browser Chrome and Brave ,the result looks same.

Brave

version: 1.11.104 Chromium: 84.0.4147.105

Chrome

version: 84.0.4147.105

在此处输入图像描述 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM