原文:https://www.quora.com/How-does-a-single-thread-handle-asynchronous-code-in-JavaScript

--------------------------------------------------------------------------------

Well, arguably its not true that Javascript is single threaded if you see from the under hood working of browser JS to your JS code, there are thread pools. By single threaded what they mean(browser end) is your JS runs into a single threaded event loop. There is one single thread that handles your event loop. Under your JS, the browser code is running multiple threads to capture events and trigger handlers, when they capture any new event, they push it on an event queue and then that event loop, in which your code is running gets triggered and it handles the request e.g. It performs an action which can be to show a DIV, which again triggers the Browser to print it, which in turn runs a thread to do it(from the thread pool).

Lets take an example of your JS algo.
window.onload 
     Show Header
     Send an Ajax Req. for config - > When done, alert a box
     Do some more page animations
So when you told the browser to send an ajax request with a provided callback, it saves it in memory and this Network IO call is transferred to a thread in Network Pool Threads, your code next to that line will continue to work. After the Network Call thread has done its job, it will push on the event queue the response. Remember that event loop? Here is when it comes to action, it picks the top entity and then trigger your callback(Context Switching on CPU Level), which in turn could be anything. Now try doing something like this.
window.onload
     Show Header
     Send an Ajax req. for config -> 
     When done -> Trigger another Ajax 
         -> for loop 0.100000000
     Do more animation

Now here, if even your second Ajax completes in due time, its callback will not be triggered until your for loop exits. Its a sort of blocking within the thread, none of the event will be fired and everything will be frozen!

Hope that clears your doubt.

Cheers!

-----------------------------------------------------------------------------------------------------------------------

Javscript is single-threaded. Each browser window has only one Javascript thread running inside them. What makes the asynchronous events possible is the browser’s Event Loop and the associated Event Queue.

Suppose Javascript engine is running some function, and in the meantime, user clicks on a button on the webpage. A Key Press event would be fired and since Javascript engine is busy doing some other work, this event would be queued in the Event Queue.

Javascript handling the Event Queue would look something like

  1. while (waitForMessage()) {
  2. processMessage();
  3. }

waitForMessage() waits for a message synchronously in the queue and when it gets one, it processes that message.

In the example above, after Javascript engine finishes executing that function, it checks for the next message in the queue. It sees that some Key Press event was fired while it was busy doing some other work. So, it handles that Key Press event either by calling any callbacks that may be bind to that key press event or doing some thing else.

But all of this happens so fast, that it feels like every thing is running parallely. But in reality, all of this is just a simple queue managed by a single thread running a infinite loop.

For information about how threads work in general , you can checkout this article.

Threading Explained

----------------------------------------------------------------------------------------------------------

You can look at the presentation at Introduction to Node js.
Though it is in context of NodeJS but the basics remain the same.
The JS runtime i.e. V8 is same in case of browser (Chrome) and Node.

Slide 12 talks about Single Threaded nature.
Slide 13-16 talk about other properties of JS like non-blocking, event driven etc.
Image on Slide 17 talks about the event loop Dron Rathore is talking about.
Analogy of working style of JS with the real word 'King and Servants' on slide 18 helps a lot understanding it as a whole.

Hope this helps.

-----------------------------------------------------------------------------------------------------------

You may have noticed that in JavaScript code every function you write returns without waiting. You never write JavaScript code that looks like this:

  1. while (true) {
  2. API.blockingCall()
  3. }

One consequence of this is that all the functions you write return to their caller as soon as they have done their thing. All the functions that call functions you write do the same thing. Ultimately, they return to the dispatcher of the single-threaded event loop. The dispatcher dequeues the next event from the event queue, identifies the function to call to handle that event and the process continues - no function ever blocks, which means every function returns to its caller in a short period of time.

So, this is how your call back function gets invoked. The function you wrote that registered the callback - and the the functions that called it - return to their caller.  Then, and only then, and only if the AJAX request is complete or has failed, does the function which implements your callback get called, but only when the dispatcher in the single-threaded event loop reaches the event that will cause that function to be invoked.

There is no magic here - no interrupting code to service a response. It is just the event loop dispatcher spinning through its queue of events, one at a time, calling functions on a single thread.

To make your mental picture complete, you need to imagine these unseen things:

* a queue of unprocessed events

* a loop that iterates through the queue of unprocessed events one at a time, and invokes the event handler function for those events.

* a mechanism that allows the result of an AJAX call to be enqueued on the queue of unprocessed events.

How does a single thread handle asynchronous code in JavaScript?的更多相关文章

  1. 多线程系列之二:Single Thread Execution 模式

    一,什么是SingleThreadExecution模式?同一时间内只能让一个线程执行处理 二,例子 1.不安全的情况 用程序模拟 三个人频繁地通过一个只允许一个人经过的门.当人通过时,统计人数便会增 ...

  2. [AngularJS NG-redux] Handle Asynchronous Operations with Middleware

    Invariably the question that comes up when talking about Redux is how does one handle asynchronous o ...

  3. 在线程内关闭thread handle,导致server crash

    很多年以前了,那时tester发现一个server crash,通过测试pager功能很多次,可以把server搞崩溃. 一般来说,能再现的bug都不难改,不过这次因为要跑很多次test,才能再现cr ...

  4. Single Thread Execution 能通过这座桥的只有一个人

    直奔主题, Single Thread Execution也称作Critical Section(临界区),范例如下: public class SingleThreadGate { public s ...

  5. A Few Words on Callbacks and Asynchronous Mechanism In Javascript

    It is said that the one of the most routine work a javascript programmer do is writing codes like &q ...

  6. 配置 VS Code 调试 JavaScript

    原文:配置 VS Code 调试 JavaScript 1. 安装 Debugger for Chrome 扩展.Open in Browser  扩展.View In Browser 扩展 2.用v ...

  7. Clean Code of JavaScript

    Clean Code of JavaScript 代码简洁之道 JavaScript 版 https://github.com/ryanmcdermott/clean-code-javascript ...

  8. 在执行一行代码之前CLR做的68件事[The 68 things the CLR does before executing a single line of your code]

    待翻译,原文地址:http://mattwarren.org/2017/02/07/The-68-things-the-CLR-does-before-executing-a-single-line- ...

  9. Current thread must be set to single thread apartment (STA) mode before OLE,当前线程不在单线程单元中,因此无法实例化 ActiveX 控件“8856f961-340a-11d0-a96b-00c04fd705a2”。

    Add the STAThreadAttribute attribute on the Main method. This attribute is required if your program ...

随机推荐

  1. GDB调试——经验总结

    GDB调试的一些很有用经验: 1. gdb调试,如果有参数,可以在run命令后加,也可以使用set args :如果是使用gdbserver+gdb的远程调试方式,参数可以在gdbserver后面加. ...

  2. 使用jdk中的java.sql包中的方法进行jdbc连接

    首先说明用 java.sql包进行jdbc连接的步骤: 1.加载数据库的驱动.(一般是oracle和mysql,oracle的数据驱动名是:Oracle.jdbc.driver.OracleDrive ...

  3. Struts2---ActionContext和ServletActionContext小结

    转载自:http://www.cnblogs.com/tanglin_boy/archive/2010/01/18/1650871.html感谢原文作者的总结 1. ActionContext 在St ...

  4. linux和shell关系

    坚持知识分享,该文章由Alopex编著, 转载请注明源地址: http://www.cnblogs.com/alopex/   索引: 什么是shell shell的分类 shell脚本的执行方式   ...

  5. 洛谷T8116 密码

    T8116 密码 题目描述 YJC把核弹发射密码忘掉了……其实是密码被加密了,但是YJC不会解密.密码由n个数字组成,第i个数字被加密成了如下形式:第k小的满足(2^L)|(P-1)且P为质数的P.Y ...

  6. 要知道的DbProviderFactory

    了解DbProviderFactory 前不久想使用下EF的通用单表增删改的特性,当时使用控制台做测试,怎么弄都没成功,原因出在app.config中,反而在mvc项目中,就没有任何问题.在反复的更改 ...

  7. BS4爬取豆瓣电影

    爬取豆瓣top250部电影 ####创建表: #connect.py from sqlalchemy import create_engine # HOSTNAME='localhost' # POR ...

  8. 【linux高级程序设计】(第十一章)System V进程间通信 4

    共享内存 共享内存主要用于实现进程间大量数据传输. 共享内存的数据结构定义: 系统对共享内存的限制: 共享内存与管道的对比: 可以看到,共享内存的优势: 1.共享内存只需复制2次,而管道需要4次 2. ...

  9. 树链剖分【p2590】[ZJOI2008]树的统计

    Description 一棵树上有n个节点,编号分别为1到n,每个节点都有一个权值w. 我们将以下面的形式来要求你对这棵树完成一些操作: I. CHANGE u t : 把结点u的权值改为t II. ...

  10. 分析dump

    一.使用jmap工具生成dump文件 二.MAT工具的下载和安装 三.使用MAT工具进行内存泄露分析  -- Step 1 :  ps –ef | grep <process> (whic ...