Javascript 是如何单线程的? [英] How is Javascript single threaded?

查看:33
本文介绍了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来通知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".

但是,要运行的下一次计划超时"总是运行 .. next.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、主机浏览器控件.例如,虽然 WebWorker 是并发运行的,但它们在不同上下文中运行,并遵循相同的异步模型(例如,由计时器使用).

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 是如何单线程的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆