我需要知道 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).
同样,setTimeout
和setInterval
也不能中断代码执行:
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/