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

  1. The first value assigned to I is 0
  2. And then say is I less than 6? If the conditions are met, the next loop is continued.
  3. SetTimeout () is supposed to be executed at this point, but due to the nature of setTimeout(), it will take a while to execute.
  4. Execute I ++, where I is assigned 1.
  5. Continue to judge that I <6 is sufficient to enter the second cycle.
  6. Until the value of I is 6, it doesn’t satisfy that I is less than 6.
  7. Stop cycle
  8. 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