简体   繁体   English

JavaScript 是否有一个事件监听器队列,不断检查是否有它们?

[英]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.我正在学习 JavaScript 并在 Chrome 开发工具或 JavaScript 控制台上添加了一些 JavaScript 代码,以延迟或阻止在几秒钟内单击网站上的任何按钮。 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? JavaScript 是否有一个事件侦听器队列,不断检查是否有任何事件侦听器并对这些事件采取行动?

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.您的while循环将阻止浏览器在请求的时间内执行的所有其他操作。 It's likely to trigger the browser "Script is taking too much time" warning popup.这很可能会触发浏览器“脚本花费太多时间”的警告弹出窗口。 That is not how you implement delays in JavaScript.这不是您在 JavaScript 中实现延迟的方式。 If you want to delay reaction to user interactions, use the timer mechanisms ( setTimeout() etc).如果您想延迟对用户交互的反应,请使用计时器机制( setTimeout()等)。

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.当您的 CPU 燃烧循环正在运行时,不会发生任何事件处理程序分派。 Once the function finishes, the event handlers will be dispatched. function 完成后,将分派事件处理程序。 The JavaScript environment is single-threaded. JavaScript 环境是单线程的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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