The single-threaded implementation of JavaScript has been smattering. It's difficult at first, but it's OK to look at it carefully.
First of all understand that JS is single-threaded, that is, JS can only process a piece of code at the same time. But JS runs the Environment browser can be multi-threaded, it has multiple threads, JS code processing engine thread, event trigger thread, HTTP request thread, timer trigger thread. Multi-Auxiliary, realize the asynchronous processing of JS.
To be exact. This actually means that the JS engine thread is the main program. Once the corresponding, such as the timer has been generated, the first time the code inside the timer hangs, wait until the need to execute, let the timer thread remind JS to execute just the code. JS this achieves pseudo-async.
SetTimeout (function() { console.log (' settime '0); Console.log (' now ');
For example, the output of the above outputs now, then output settime.
This is a diagram that makes me feel the clearest. The blue whole represents the part of the code to be executed in the JS engine. The block of Blue JavaScript is now part of the code to execute when we want to go interval or click events and so on, things need to go back. The subsequent code is processed until the current execution finishes. But there are some differences between settimeout and SetInterval, and settimeout, if produced, puts things in a sequence that waits to be processed, but settimeout each time it destroys the trigger, it retains only the part of the code that needs to be executed for the first time. If the second need to trigger, where the JS engine is used, the callback will trigger the discard. Until the JS section is idle, it will be executed immediately.
Detailed Standard:
Http://www.cnblogs.com/sprying/archive/2013/05/26/3100639.html
JavaScript single Thread implementation