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.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b31868-2b51b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b31868-2b51b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?