gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:09:39 24 4
gpt4 key购买 nike

我需要知道 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com