Let's not look at the following content. Let's take a look at the short code below. How much should I pop up?
var t=null;var i=0;function a(){ i++; if(i==20){ return; } t=setTimeout(a,17);}a();alert(i);
This is a problem I encountered when writing results today. When I set a timer to do the loop, the following program starts running without the end of my loop.
The answer to the above procedure is "1 ".
So why did the program start running alert (I) in a hurry before the loop is completed?SetTimeout Principle.
ActuallyOnce the setTimeout and setInterval timers are triggered, they are executed in parallel with the js program, that is, they are not in a single time line.The timer is only used to make a plan, that is, to execute the target method at intervals.
For example, we make a weekly plan to go out every weekend. This is actually a timer, which goes out to play every seven days. But we still need to go to work from Monday to Friday. That is to say, we can't leave the team from Monday to Friday because we went out to play on weekends.
The same is true for js programs. I will finish the timer task at that time, but I will continue to execute the following code at other times. When the above program and function a run to the previous sentence of the timer, the value of I is 1, and then the timer is executed, 17 milliseconds is much larger than the running time of the program, so js does not continue to execute, so alert (I), that is, 1.
To prove that the timer is not lazy, We will pop up I at intervals, the following program:
var t=null;var f=null;var i=0;function a(){ i++; if(i==20){ return; } t=setTimeout(a,17);}function b(){ alert(i); f=setTimeout(b,17);}a();b();
We can see that I is indeed increased from 0 to 20.
The above statement is summarized as one sentence, that isThe timer and other js programs are executed in parallel and do not affect each other!
The program at the beginning should be written as follows:
var t=null;var i=0;function a(){ i++; if(i==20){ alert(i); return; } t=setTimeout(a,1);}a();
After you perform operations at the exit of the program, I (I = 20) is displayed correctly ).