How does a single thread handle asynchronous code in JavaScript?
Posted 牛顿的小脑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了How does a single thread handle asynchronous code in JavaScript?相关的知识,希望对你有一定的参考价值。
原文: 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!
以上是关于How does a single thread handle asynchronous code in JavaScript?的主要内容,如果未能解决你的问题,请参考以下文章
[转载] How Many Partitions Does An RDD Have
How does Circus stack compare to a classical stack?
How Long Does it Take to Learn or Become a UI/UX Designer?
Does Daemon Thread Exit with Main Thread?
How many seconds does this period last的中文是啥
OGG How to Resync Tables / Schemas on Different SCN s in a Single Replicat