There is the following code:


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

Why did you make six sixes?

It has to do with when the function is executed. The setTimeout function prints immediately after the function is executed. At this point, the for loop has finished running, the value of the global variable I has changed to 6, and since the setTimeout function has been executed six times, six sixes are typed.

How do I get this function to print 0,1,2,3,4,5

Since the variables declared by the let keyword are block-level scoped, consider declaring variables into the for loop so that a different I variable is created each time the function executes. The code is as follows:



for(let i = 0; i<6; i++){         // Change I to a local variable
  setTimeout(() = >{
    console.log(i)
  },0)}/ / 0,1,2,3,4,5
Copy the code

discuss

It can also be analyzed from the perspective of variable scope. The first way I write it is when the function is called after the whole function has run, and it’s run and I is 6, six times, so it’s 6 6.

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

The second way to write it, I is a local variable that gets printed out every time it runs, and then generates a new I again. The verification is as follows:

for(let i = 0; i<6; i++){         // Change I to a local variable
  setTimeout(() = >{
    console.log(i)
  },0)}console.log(i)              
//Uncaught ReferenceError: i is not defined
/ / 0
/ / 1
/ / 2
/ / 3
/ / 4
/ / 5
Copy the code

The second method I is not a global variable, trying to print I found an error.

thinking

Since local variables can be used to solve this problem, can the immediate execution of JS functions also be used to solve this problem?

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

Yes, but it’s just one person’s opinion, or it could just be a blind encounter. I believe that I will have a deeper understanding of this problem with the further study.