No more code nonsense

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

The output is not what we would normally expect it to be why, why is it not 0 through 5? This is because the code specified by setTimeout() will not be executed until all code has been executed. That is, the for loop doesn’t turn until it finishes executing

A delay of 0 means execution “immediately”, or as soon as possible. In fact, the actual delay is longer than the set value. In browsers, setTimeout() has a minimum interval of 4ms per call

The variable I is declared by the var command and is valid in the global scope, so there is only one variable I in the global scope. Every time the value of variable I changes, setTimeout() is executed at the end of the loop, and the value of I is 6, so six 6’s are printed

Is there any way to make your code behave logically?

Method 1: For and let are used together

for(let i = 0; i < 6; i++){
  setTimeout(() = >{
    console.log(i)
  },0)}Execute output 0,1,2,3,4,5
Copy the code

The variable declared by let is valid only for this loop, so each loop’s I is actually a new variable. The JavaScript engine internally remembers the value of the previous cycle, and when it initializes the variable I of this cycle, it evaluates on the basis of the previous cycle.

Method 2: Use the third parameter of setTimeout

for(var i = 0; i < 6; i++){
  setTimeout(() = >{
    console.log(i)
  },0,i)
}
Execute output 0,1,2,3,4,5
Copy the code

Additional parameters, which are passed to function as parameters once the timer expires

Method three: Use closures

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