Explain when the function is executed

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

Q: Why are six sixes printed? First, let’s look at a few things about setTimeout()

  • The fastest execution time of setTimeout is 4 milliseconds.
  • Functions that use setTimeout will execute slower than the current queue functions, after them.
  • The timer in setTimeout is not the exact time. In fact, it needs to be executed after the previous function is executed.

In the code, the for loop is executed first, and then setTimeout() is executed. When the for loop is executed, the last value of I is 6, so it prints out six 6’s

  • SetTimeout () can also be learned by referring to the MDN documentation.

How to print 0 to 5?

for(let i = 0; i<6; i++){
  setTimeout(() = >{
    console.log(i)
  },0)}Copy the code
  • In the code above, variablesiisletDeclared, currentiIt only works in this cycle, so every cycleiIt’s actually a new variable.
  • Check out this article to learn moreletandvarSome of the differences betweenLet and const commandsOr consult the MDN documentation

Other methods of printing 0 to 5

I also found two other ways to achieve this effect online

  • usesetTimeoutThe other is to use closures (note: prior to ES6) :
// The first method
for (var i=0; i<6; ++i) {
    setTimeout(function(i){
        console.log(i)
	}, 0, i)
}
// The second method
for(var i=0; i<6; ++i) { ! (function(j) {
        setTimeout(function(){
            console.log(j)
            }, 0)
	})(i)
}
Copy the code

The use of setTimeout() and for,let, and setTimeout().