One, the phenomenon

This article mainly discusses the JS execution mechanism, first look at a small white in learning JS more difficult to understand the code:

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

When you start learning, you think this code should print out 0, 1, 2, 3, 4, 5, but it turns out to be six 6’s.

Second, the reason why

  • Why do I get a 6

This has to do with the call mechanism of setTimeout (asynchronous execution of JS). SetTimeout is executed after the end of the for loop, and by the end of the for loop, I has already changed to 6, because when I = 5, the for loop condition is still valid, and I ++ is executed again, and finally I = 6, This value is out of the for condition, and the for loop ends, and setTimeout prints 6.

  • Why are there six 6’s

For actually executes 0,1,2,3,4,5 times, and each time setTimeout sets an alarm clock to hit I (6 alarms are set). Hold down the clock and wait until the end of the for loop, at which point I has become 6, and the alarm clock rings one by one. Conger prints out six sixes

How to print 0,1,2,3,4,5

The main idea is through scope, there are two ways:

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

The declaration of I is placed inside the for loop, so each time the loop declares a new I and forms a block-level scope. The six scopes do not affect each other, so the value of each I is preserved.

  • Method 2
for(var i = 0; i < 6; i++ ){
  !function (j){
    setTimeout(() = > {
      console.log(j)
    },0)
  }(i);
}
/ / 0,1,2,3,4,5
Copy the code

With immediate execution functions, an immediate execution function is formed for each loop.