I would like to ask you, why is the result of the execution of this code 0meme1jin2? Why would clearTimeout erase the last loop?

function fn1(){
    for(var i=0;i<4;iPP){
        var tc=setTimeout(function(i){
            console.log(i);
            clearTimeout(tc)
        },10,i);
    }
}
fn1()
May.23,2022

1. Each time setTimeout produces a new id
2. All events within the setTimeout are queued in another process to execute
3. When the setTimeout is executed four times, the tc becomes the id
4 of the last event. When you start executing an event in setTimeout, all the tc obtained by setTimeout () is the id of the fourth event
" where there is the same


first of all, we make sure that for (var item0 for I < 4x IPP) {var b ='a'}; console.log (b); will output a , which proves that the curly braces of for do not create a new scope, and the result of changing var to let will be different. You can try.

in that case, I is scoped function independently, so each time the result is the I of the current loop. Tc, which is in public scope, retains the last value, so the tc is cleared the first time it is executed.

clipboard.png


after the for loop has been executed four times, the next four timers defined will be executed But because the tc is defined four times in the for loop, each definition will re-assign the last tc, which is equivalent to defining tc four times, and only the last time is effective, so only the last time tc


your tc variable is updated to the currently defined timer id for each loop, and tc equals the last timer id when the loop ends. And because the execution of setTimeout is delayed, by the time the timer executes the code, the loop will be over long ago, that is, tc is equal to the last timer id , so it will actually be output only three times, because the first three timer execution is to clear the tc timer.

Menu