原文: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!
原文地址:https://www.cnblogs.com/oxspirt/p/9087366.html