1 Explain why the following code prints six 6’s

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

For each for loop, setTimeout is executed once, but the function inside is not executed. Instead, it is placed in a task queue. The for loop is executed six times, and then released six times. When the main thread completes, it enters the task queue for execution. Now because the for loop is I =6, the output is all 6.

Write a method to make the above code print 0, 1, 2, 3, 4, 5

Method 1: let keyword

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

Because variables declared by let in a for statement are local variables that follow block scope and can only be used in the current function, each time the for loop executes, a separate scope is generated and a new I is generated, equivalent to six I’s. Each time setTimeout() is executed, the corresponding I is printed, so the result is 0, 1, 2, 3, 4, 5.

Method two: closures

 let i 
    for(i = 0; i <6; i++){ !function(i){
            setTimeout(() = >{
                console.log(i)
            },0)
        }(i)
    } / / 0,1,2,3,4,5
Copy the code
  • Function (value){} wrap setTimeout()
  • Then add the operator to the front of the anonymous function! To prevent new global variables from being generated
  • An anonymous function is immediately called by adding a () to it and passing in I as value

Method 3: Use the third parameter of setTimeout to pass in I

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

Principle: The third argument with setTimeout can pass itself to the first argument, the anonymous function function(value), as the required argument value. Value can be left unwritten by default and I passed six times, (0,1,2,3,4,5). The anonymous function prints out a third triplet that is usually not written. If the third parameter is not written by default, the function is not passed in

Method 4: const keyword

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