A piece of code that’s a little hard to understand

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

When we first look at the code, we assume that it will print 0-5 (0 to 5). But the final output is six sixes. The diagram below:

Here’s why:

  1. setTimeout()The call to the function changes the code logic. So we’re going to export it0 to 5The resulting code looks something like this:
let i = 0;
for(i = 0; i < 6; i++){
    console.log(i);
}
Copy the code

The logic of this code is that I is printed every time it enters the loop. By contrast, the logic of the code discussed in this chapter is that the code with the setTimeout() function counts from 0 to 6 at a time, and then prints it, and so on for six rounds of complex numbers. Why do we count to six? Because 6 doesn’t happen to satisfy the condition that it’s less than 6, and then it breaks out of the loop, so 6 is printed.

How can I output 0 to 5 after setTimeout

Simply use the let in the for loop. Modify the code as follows:

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

So you’re going to have a new variable every time you go in.