简体   繁体   中英

Does JavaScript have a queue of event listeners that constantly checked if there are any of them?

I am learning JavaScript and I added some JavaScript code on Chrome Dev Tools or JavaScript Console to delay or block clicking any button on a website in a number of seconds. And it worked as expected. However, that click triggered automatically after a couple of seconds. Why might that be? Does JavaScript have a queue of event listeners that constantly checked if there are any of them and act on those events?

function hang(secs) {
    const doneAt = Date.now() + (secs * 1000)
    while (Date.now() < doneAt) {}
}

hang(10)

Your while loop will block everything else the browser is doing for the amount of time requested. It's likely to trigger the browser "Script is taking too much time" warning popup. That is not how you implement delays in JavaScript. If you want to delay reaction to user interactions, use the timer mechanisms ( setTimeout() etc).

As to your question specifically, events do in fact queue up, but nothing is "constantly checking" them; an event happens, and that simple fact causes an action to be put on the queue. While your CPU-burning loop is running, no event handler dispatches can occur. Once the function finishes, the event handlers will be dispatched. The JavaScript environment is single-threaded.

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