Example 1 explain why the following code prints six 6’s
let i = 0
for(i = 0; i<6; i++){
setTimeout(()=>{
console.log(i)
},0)
}
Copy the code
First we need to look at the setTimeout function. Remember that setTimeout is an asynchronous function, so this code will go through the entire loop, at which point I will be 6, and then six console.log(I) will be executed, so only six 6s will be printed.
So is there any way I can solve this problem, so I want to do this, and then I want to print out 0, 1, 2, 3, 4, 5. Yes, it just needs to be changed a little bit.
Example 2 write a way to get the above code to print 0, 1, 2, 3, 4, 5
for(let i = 0; i<6; i++){
setTimeout(()=>{
console.log(i)
},0)
}
Copy the code
Do not find, just change the position of let, when the combination of for and let, can have such a miracle effect, this is JS love to xiaobai.
Is there any other way? Before ES6, there were two other ways, one using the third parameter of setTimeout and the other using closures.
Example 3 Other methods implement this function
// The first method
for (var i=0; i<6; ++ I){setTimeout(function(I){console.log(I)}, 0, I)} i<6; ++i) { ! (function(j) { setTimeout(function(){ console.log(j) }, 0) })(i) }Copy the code