Single thread concept of JavaScript running in browser

浪尽此生 提交于 2019-12-18 11:29:13

问题


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.

The book has to say this :

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.

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).


回答1:


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)

EDIT to answer your edit:

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).

EDIT: 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.

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

+2 years after the last EDIT: 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.




回答2:


@alexandernst

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.

This is happening because the event loop doesn't get to handle the events. If you wait for the loop to complete, you'll find all the text, you wrote while the the loop was running, appear.

That means that you have a separate thread picking up the input events and putting them on the queue.



来源:https://stackoverflow.com/questions/16749664/single-thread-concept-of-javascript-running-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!