<Script> for(varI=0; I<2; I++) {setTimeout (function() {console.log (i); },0); } </Script>Results: 2,2
Print two 2 instead of 0, 1, which is related to the JS execution sequence.
There are two types of tasks, one synchronization task and one asynchronous task. A synchronization task is a task that is queued on the main thread. An asynchronous task is a task that goes into the task queue without entering the main thread, and only the task queue notifies the main thread that an asynchronous task can execute and the task goes into the main thread execution.
(1) All synchronization tasks are performed on the main thread, forming an execution stack (execution context stack).
(2) In addition to the main thread, there is a task queue. As long as the asynchronous task has a running result, an event is placed in the task queue.
(3) Once all the synchronization tasks in the "execution stack" have been executed, the system reads the "task queue" to see what events are in it. Those corresponding asynchronous tasks, so end the wait state, go to the execution stack, and start execution.
See Nanyi JavaScript operating mechanism for details. Links: http://www.ruanyifeng.com/blog/2014/10/event-loop.html
The SetTimeout function is an asynchronous task, the for loop is a synchronous task, and the function in SetTimeout is a callback function. The order of execution is: Synchronization priority, asynchronous pull over, callback bottom. So even if the settimeout time parameter is 0 it will still be placed in the task queue instead of the main thread. The main thread performs the asynchronous task settimeout after the for loop is executed. In addition settimeout () simply inserts the event into the "task queue" and must wait until the current code (execution stack) finishes executing, before the main thread executes the callback function it specifies. If the current code takes a long time, it may take a long time, so there is no guarantee that the callback function will be executed at settimeout ().
<Script> for(varI=0; I<2; I++){ (function() {console.log (i); } (i))}</Script>
Results: 0,1
Replace the function immediately, the 0,1 will be printed.
The analysis of JS synchronous asynchronous execution sequence settimeout face question