在浏览器中运行的JavaScript单线程概念 [英] Single thread concept of JavaScript running in browser

查看:194
本文介绍了在浏览器中运行的JavaScript单线程概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下图是从由Jon Resig的的JavaScript的忍者的书秘密的第3章拍摄。在这里,笔者解释了浏览器事件循环。

The following figure is taken from Chapter 3 of the book Secrets of the JavaScript Ninja by Jon Resig. Here the author is explaining the browser event loop.

这本书有这样说:

要注意这一点很重要是使事件的浏览器机制
  到队列外在于这一事件循环模式。处理
  必要,以确定何时发生的事件,并将其推到
  事件队列不参与该在处理的线程
  事件。

It’s important to note that the browser mechanism that puts the events onto the queue is external to this event loop model. The processing necessary to determine when events have occurred and to push them onto the event queue doesn’t participate in the thread that’s handling the events.

所以我的问题是,正确的说,JavaScript的浏览器是单线程的?我问这个问题,因为显然两个独立的任务(处理事件和事件queing并行怎么回事)。

So my question is it correct to say that JavaScript in browser is single threaded? I ask this question because clearly two separate tasks(processing the events and event queing are going on in parallel here).

推荐答案

JavaScript是单线程的任何地方,在一个浏览器或的NodeJS。它从不应该支持多线程以任何方式(也可能是,如果有人实现了某种多线程的JS引擎,不好的事情会发生,这是肯定)

JavaScript is single-threaded anywhere, in a browser or in NodeJS. It never was supposed to support multithreading in any way (and probably if somebody implements a JS engine with some kind of multithreading, bad things will happen, for sure)

编辑回答您的编辑:

这事件队列填充有从浏览器的主循环数据(鼠标/ kb的事件,网络事件等)。运行的JS同一主循环。您发布的数字是正确的,但它(种)模糊了现实。据我所知,只有一个线程处理一切(即,填充队列并运行,线由行,任何JS code)的

That event queue is filled with data (mouse/kb events, network events, etc) from the main loop of the browser. That same main loop that runs JS. The figure you post is correct but it (kind of) blurs the reality. AFAIK Only one thread handles everything (that is, filling the queue and running, line-by-line, any JS code).

编辑:一种方式来证明这一点:创建一个很长的环路和一个文本区域。尝试循环运行时在文中写的。你不能。这是因为在主循环忙于运行循环,因此它不能处理事件KB

One way to prove this: Create a really long loop and a text area. Try to write in the text are while the loop is running. You can't: it's because the main loop is busy running the loop so it can't handle the kb events.

编辑:这似乎是一个很好的答案:<一href=\"http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded?rq=1\">Is JavaScript的保证是单线程?

This seems to be a really good answer: Is javascript guaranteed to be single-threaded?

最后一次编辑后2年:这个答案越来越有点老脱离现实。 io.js(node.js的,并在这之后,可能CHROM [E | IUM],FF,Safari浏览器后)朝向多进程的支持推(通过工人)。您可以查看更多关于这里

+2 years after the last This answer is getting a little bit old and detached from reality. io.js (and node.js after that, probably Chrom[e|ium], FF, Safari after that) is pushing towards multiprocess support (via workers). You can check more about that here.

这篇关于在浏览器中运行的JavaScript单线程概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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