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);
这个时候,他是同时输出的,为什么跟上面用i的不一样?
谢谢各位的回答哈。
First, 5 timers are created in the loop body. Each timer has its own ID. The ID starts executing after the call
setTimeout
时被返回,是一个数值。其次,
timer
只是保存定时器的ID,并不会修改定时器的ID,所以当循环结束时,timer
只是保存了最后一个定时器的ID。赋值覆盖的是什么应该清楚了吧。定时器里的函数是在
clearTimeout
is executed. So the last timer is cleared. Other timers are executed as usual.The last one,
while
执行的时候setTimeout
里的函数并没有被调用,因此j++
并没有执行,所以在循环体内j
一直是0
。注:匿名函数只是作为一个参数被传入
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
执行的时候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