Javascript如何单线程?

编程入门 行业动态 更新时间:2024-10-16 00:26:17
本文介绍了Javascript如何单线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对Javascript的单线程性质有疑问。

I have a question about the single threaded nature of Javascript.

console.log("1"); setTimeout(function(){console.log("2");},3000); console.log("3"); setTimeout(function(){console.log("4");},1000);

此代码的结果是 1 3 4 2 。如你所见, 4 在 2 之后出现,这让我想知道在单线程环境中不应该 2 来自 4 ?如果没有,那么为什么JS知道第二个 setTimeout 应该在第一个之前完成?不应该有两个线程同时工作以完成两个 setTimeout s以通知 EventLoop ?

The result of this code is 1 3 4 2. As you see, 4 comes after 2 which makes me wonder that in a single threaded environment shouldn't 2 have come after 4? If not, then how come JS knows the second setTimeout should finish before the first one? Shouldn't there be two threads which work concurrently to complete the two setTimeouts in order to notify EventLoop?

推荐答案

JavaScript(在浏览器中)不并发运行 2 。

JavaScript (in browsers) doesn't run concurrently2.

最多一个的 setTimeout 回调可以一次执行 - 因为有一个 JavaScript执行上下文或线程。

At most one of the setTimeout callbacks can execute at a time - as there is one JavaScript execution context or "thread".

但是,要运行的下一个计划超时始终运行..下一步。 4在2回调之前运行,因为计划提前运行。超时是从同时有效安排的(没有任何操作被阻止),但是2的间隔时间更长。

However, the "next scheduled timeout" to run is always run .. next. The "4" runs before the "2" callback because it was scheduled to run sooner. The timeouts were effectively scheduled from the same time (none of the operations were blocking), but "2" had a much longer interval.

底层实现可能使用线程 1 - 但同一全局上下文中的JavaScript不会并发运行并保证一致和原子行为。

The underlying implementation may use threads1 - but JavaScript in the same global context doesn't run concurrently and guarantees consistent and atomic behavior between all callbacks.

1 或它可能不会;这可以在 select / poll 实现中没有任何线程的情况下处理。

1 Or it may not; this can be handled without any threads in a select/poll implementation.

2 在相同的上下文中:即Tab / Window,WebWorker,主机浏览器控件。例如,当WebWorkers同时运行时,它们会在不同的上下文中运行,并遵循相同的异步模型(例如,计时器使用的)。

2 In the same context: i.e. Tab/Window, WebWorker, host Browser Control. For example, while WebWorkers are run concurrently they do so in different contexts and follow the same asynchronous model (eg. as used by timers).

更多推荐

Javascript如何单线程?

本文发布于:2023-06-01 18:24:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/422837.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单线程   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!