1. Look at the code below

let i = 0
for(i = 0; i<6; i++){
 setTimeout(()=>{
   console.log(i)
 },0)
}
Copy the code

The result of the above code is six sixes. Why? Because the for loop completes before any setTimeout function, and the value of I is 6 after the for loop ends, print six sixes

2. How do I make the above code print 0,1,2,3,4,5

This is as simple as using the let keyword when the for loop declares and initializes variable I as follows:

for(let i = 0; i<6; i++){
  setTimeout(()=>{
    console.log(i)
  },0)
}
Copy the code

3. What other methods can be used besides the let keyword mentioned above?

  • Place the increment of a variable in the body of setTimeout
let i=0
let j=0
for(i = 0; i<6; i++){
  setTimeout(()=>{
    console.log(j)
    j++
  },0)
}
Copy the code
  • Use local variables to hold increment values
let i=0
for(i = 0; i<6; i++){
  function fn()
  {
  let a=i
  setTimeout(()=>{
    console.log(a)
  },0)
  }
  fn()
}
Copy the code
  • Use immediate execution functions
let i=0 for(i = 0; i<6; i++){ ! function() { let a=i setTimeout(()=>{ console.log(a) },0) }() }Copy the code