Why does the following code print six sixes
let i = 0
for(i = 0; i<6; i++){
setTimeout(()=>{
console.log(i)
},0)
}
Copy the code
SetTimeout (): Sets a timer that executes a function or a specified piece of code after the timer expires. So the setTimeout() of the code above is executed at the end.
In the for loop
- The first value assigned to I is 0
- And then say is I less than 6? If the conditions are met, the next loop is continued.
- SetTimeout () is supposed to be executed at this point, but due to the nature of setTimeout(), it will take a while to execute.
- Execute I ++, where I is assigned 1.
- Continue to judge that I <6 is sufficient to enter the second cycle.
- …
- Until the value of I is 6, it doesn’t satisfy that I is less than 6.
- Stop cycle
- At this point, setTimeout() in the previous six loops starts executing and prints the I that appears.
Because in this loop, setTimeout() is executed six times and at the end, and the last I is 6. So it prints out six 6’s.
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
- Because JS adds stuff when you use for and let together
- And each time the loop creates one more I
In addition to using the for let coordination, print the methods 0, 1, 2, 3, 4, 5
Use immediate execution functions
let i = 0
for(i = 0; i<6; i++){
!function(i){
setTimeout(() = >{
console.log(i)
},0)}(I)} Copy the codeCopy the code
You can also use the third argument of setTimeout
let i = 0
for(i = 0; i<6; i++){
setTimeout((i) = >{
console.log(i)
},0, I)} copy codeCopy the code
Use the const keyword
let i
for(i = 0; i<6; i++){
const x = i
setTimeout(() = >{
console.log(x)
})
}
Copy the code