var?i?=?0,?timer,?j?=?0;
while(i++?<?5)?{
??timer?=?window.setTimeout(function(){
????j++;
????alert(j);
??},?1000);
}
clearTimeout(timer);
The output is 1,2,3,4
5 why is it not output? And why is it output like this? Doesn't he assign values ??and overwrite them every time? Why is it still being executed? What is the order? When is the statement clearTimeout executed?
If you change it slightly
var i = 0, timer, j = 0;
while(i < 5) {
timer = window.setTimeout( function(){
j ;
alert(j);
}, i*1000);
}
clearTimeout(timer);
This means output every second , if the above problem is solved, then there is nothing wrong
Continue to change
var?i?=?0,?timer,?j?=?0;
while(i++?<?5)?{
??timer?=?window.setTimeout(function(){
????j++;
????alert(j);
??},?j*1000);
}
clearTimeout(timer);
這個(gè)時(shí)候,他是同時(shí)輸出的,為什么跟上面用i的不一樣?
謝謝各位的回答哈。
小伙看你根骨奇佳,潛力無(wú)限,來(lái)學(xué)PHP伐。
First, 5 timers are created in the loop body. Each timer has its own ID. The ID starts executing after the call setTimeout
時(shí)被返回,是一個(gè)數(shù)值。
其次,timer
只是保存定時(shí)器的ID,并不會(huì)修改定時(shí)器的ID,所以當(dāng)循環(huán)結(jié)束時(shí),timer
只是保存了最后一個(gè)定時(shí)器的ID。賦值覆蓋的是什么應(yīng)該清楚了吧。
定時(shí)器里的函數(shù)是在clearTimeout
is executed. So the last timer is cleared. Other timers are executed as usual.
The last one, while
執(zhí)行的時(shí)候setTimeout
里的函數(shù)并沒(méi)有被調(diào)用,因此j++
并沒(méi)有執(zhí)行,所以在循環(huán)體內(nèi)j
一直是0
。
注:匿名函數(shù)只是作為一個(gè)參數(shù)被傳入setTimeout
in the function.
First question, when i=4, it should have alert(j==5) after 1 second, but then clearTimeout(timer) was executed immediately to cancel alert(j)
The second question is the same as above
The third question, when i=0, j is 0, you may think that the alert operation will be executed directly, but it is not the case. setTimeout(code, millisec) puts the code into a waiting queue and then executes it later, so When i=1, j is still 0. Similarly, i=2,3,4,5, so 1234 will be output continuously
Because all setTimeout
是在clearTimeout(timer)
we started executing after that, the fifth one has already been cleared.
The last one is executed after while
執(zhí)行的時(shí)候j
是0
,所有的setTimeout
都是延遲0
.
Take a good look at this while(i++ < 5) why it cannot output 5 because it is not larger than 5. Solution while(i++ <= 5)
Let’s answer the first one, because setTimeout is executed asynchronously, so clearTimeout(timer) will clear the first timer. That is to say, when i=0, the alert will not come out, j has not executed j++, and j is still equal to 0. After one second, the timer is generated again. At this time, i=1,j=0. Since the subsequent clearTimeout(timer) is executed synchronously, the timer is no longer cleared, so you can see your current results