javascript - 浏览器事件会中断 JavaScript 代码执行吗?

标签 javascript

我需要知道 Javascript 事件是否优先于正常代码执行。我的意思是这会中断代码执行吗?我希望用户从下拉列表中选择一些值,选择后对其执行一些处理,然后将其发布到服务器。 但是,如果用户在经过特定时间后没有选择值,我会以编程方式从下拉列表中选择一些值(基于预定义的规则),并在处理后将其发布到服务器。现在我担心,如果我以编程方式从下拉列表中选择某个值,并且在处理该值时,用户也可能从用户界面中选择某个值,并且数据会两次发布到服务器。 虽然Javascript是单线程的,但我读到一些事件会中断正常的代码执行。如果这是真的,我该如何解决该问题。

最佳答案

浏览器事件不会中断 JavaScript 代码的执行。 JavaScript 实际上是单线程的,并且具有先进先出 (FIFO) message queue用于执行代码。关于抢占:

Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates).

同样,setTimeoutsetInterval也不能中断代码执行:

Calling setTimeout will add a message to the queue after the time passed as a second argument. If there is no other message in the queue, the message is processed right away; however, if there are messages, the setTimeout message will have to wait for other messages to be processed. For that reason the second argument indicates a minimum time and not a guaranteed time.

关于javascript - 浏览器事件会中断 JavaScript 代码执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45289214/

相关文章:

javascript - 部分 View 中的明确值(多个)

javascript - 如何获取 yandex map 上单击的地标的 ID?

javascript - 复制元素时,jQuery 单击事件不会触发

javascript - 在 D3 中用线连接矩形

javascript - 等待代码完成 Ionic 生命周期

JavaScript。如何将问题和正确答案返回到 Math.random

javascript - 您将如何在控制台中终止无限循环 (`setInterval` )?

Javascript async parallel - 如何返回最终结果/回调?

javascript - 从 Angular 外部设置 Angular 组件的属性

javascript - 设置要下降的列的基值