We all know that JS functions have many key elements, such as call timing, scope, formal parameters, call stack, function promotion and so on. But when we study JS functions, the first element that needs to be clarified is when they are called, that is, when they are executed. Let’s take a look at this example:

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

When we execute the above function, JS will declare an I variable and set its value to 0, then execute the for loop in turn — first set I to 0, then determine if I is less than 6, if so, execute setTimeout and then print out the value of I, and I ++; If not, end the loop.

But!

Due to the delay nature of the setTimeout method, the value of I is not printed in each for loop. Instead, the value of I is printed after the entire for loop is complete. But every time the for loop is executed, one of the values of I is printed out, six times in total, so six of the values of I are printed out. The value of I will be printed later in each loop, so every time I is printed it will have executed 6 times I ++, so the printed value will be 6 6’s.

Is there a way to make the function print 0,1,2,3,4,5 without changing the for/let combination?

B: Sure.

We just need to put the let in the for loop, so that we can treat each I value as a complete function execution, so that setTimeout does not have to wait for the entire for loop to execute.

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

Is there any other way to print 0,1,2,3,4,5?

Yes, there is, and that is to add an immediate function that can save the value of I each time, so that when you break out of the loop you can still print out the value of the saved I.

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

© This summary course copyright belongs to the author, reprint need to indicate the source