The kernel of the browser is multi-threaded, and they mate with each other in the kernel to keep in sync, and a browser implements at least three resident threads: JavaScript engine thread, GUI render thread, browser event trigger thread.
JavaScript execution Order: http://bbs.html5cn.org/thread-80116-1-1.html
1.javascript engine is based on the event-driven single-threaded execution, JS engine has been waiting for the task queue of the arrival of the task, and then to deal with, the browser whenever there is only one JS thread running JS program.
The 2.GUI rendering thread is responsible for rendering the browser interface, which executes when the interface needs to be redrawn (Repaint) or when a return (reflow) is triggered by an operation. However, it is important to note that the GUI rendering thread is mutually exclusive to the JS engine, and when the JS engine executes, the GUI thread is suspended, and the GUI update is saved in a queue until the JS engine is idle and executed immediately.
3. The event triggers the thread, and when an event is triggered the thread adds the event to the end of the queue to be processed and waits for the JS engine to process. These events can come from code blocks currently executing by the JavaScript engine, such as settimeout, other threads from the browser kernel such as mouse clicks, Ajax asynchronous requests, and so on, but because of the JS single-threaded relationship all of these events are queued for the JS engine to process.
4. Even if the settimeout is 0, he is also waiting for the JS engine's code to be inserted into the JS engine thread's final execution after execution. JS working mechanism is: when the thread does not execute any synchronization code under the premise of executing asynchronous code, settimeout is asynchronous code, so settimeout can only wait for JS idle to execute, but the dead loop is never idle, so settimeout will never execute.
Example:< input type= "text" value= "a" name= "input" onkeydown= "Console.log (this.value)"/>< input type= "text" value= "a" name= "input" onkeydown= "var me=this;settimeout (function () {Console.log (Me.Value) },0) "/>Analysis: The first in the KeyDown, the bounce is input in the original value, and the 2nd in KeyDown, but can pop up the updated value, is because settimeout, although his delay is set to 0, almost instantaneous trigger, But it was added to the execution queue, but this is the process, the rendering is done, and when his callback function executes, the output is already the updated value.
JS event threading mechanism and asynchronous execution