码迷,mamicode.com
首页 > 编程语言 > 详细

How does a single thread handle asynchronous code in JavaScript?

时间:2018-05-25 13:32:53      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:back   conf   err   get   code   complete   cal   rem   contex   

原文: 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?

标签:back   conf   err   get   code   complete   cal   rem   contex   

原文地址:https://www.cnblogs.com/oxspirt/p/9087366.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!