The problem of using setTimeout in the for loop, the advanced version

A problem I saw in Zhihu, I don"t understand why the result is 123

.
for(var i=1;i<=4;iPP){
    var time=setTimeout(function(i){
        clearTimeout(time);
                console.log(i);
    },1000,i);
}

/ / output results 1, 2, 2, 3

Jun.19,2022

print a console.log ("cleartime:", time) , and you can see why the last 4 didn't print out.

for (var i = 1; i <= 4; iPP) {
    var time = setTimeout(
        function(i) {
            console.log("cleartime:", time);
            clearTimeout(time);
            console.log(i);
        }, 1000, i );
}

cleartime: 4
1
cleartime: 4
2
cleartime: 4
3

that is, although I sharing is avoided by passing parameters through a timer, var time is shared, and each time ID 4 is cleared, so the last 4 is not printed.


this is because the for loop is synchronous, while the time module, such as setTimeOut, is asynchronous. After the asynchronous is finished, the asynchronous may still be being processed, so the result will be earlier than the previous operation. As for why it is not 1234 because every time you know the timeout call, you do not meet the conditions to exit the loop and finally output 123.

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-1b3b52e-2c278.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-1b3b52e-2c278.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?