In different cases, js functions can have different results
Ex. :
let i = 0
for(i = 0; i<6; i++){
setTimeout(() = >{
console.log(i)
},0)}//6
Copy the code
The result of this code is six sixes, not the zero to five we subconsciously think. Why is this?
This is because the above code contains the setTimeout function, which simply means that the code will be executed later. You can set too much time to execute the code, in milliseconds
why
Because setTimeout is executed asynchronously, it is executed after a while. So in the above for loop, setTimeout is executed once each time, but the function inside is not executed. It will be put into the task queue, and after the for loop, setTimeout will execute the function inside, printing out six sixes
Other methods print 0 to 5
1. Use let in the for loop
for(let i = 0; i<6; i++){
setTimeout(() = >{
console.log(i)
},0)}// 0 1 2 3 4 5
Copy the code
This binds I to the for loop, and every time the I in the loop is the new I, each time the JS loop remembers the value, copies it, and the next loop recalculates from that value. When the for loop ends, steTimeout prints I with a value between 0 and 5
2. Use closures
for (var i=0; i<6; i++) {
(function(j) {
setTimeout(() = > {
console.log( j );
}, j*1000 );
})(i);
}
//0 1 2 3 4 5
Copy the code
Because the actual parameters are strongly dependent on timer I, we use closures to keep the variable of I in memory, output j with references to the variable of external I, and the value of I is determined each time through the loop. So it prints 0 to 5
3. Use the third parameter of steTimeout
for (let i=0; i<6; i++) {
setTimeout( function timer() {
console.log( i );
}, 0, i );
}
Copy the code
Each time the argument is passed in is the value of I in the for loop, so it prints 0 to 5
Pay attention to
Methods 2 and 3 are found on the Internet, some specific principles are not known, and may be explained separately after understanding