Call timing is a very important number of JS functions, call timing is different, the results will be different.

First, sample code:

let a =1 
functon fn(){
    console.log(a)
}
a = 2
fn()
Copy the code

Print 2, because fn() is called after a=2.

There is also the following code:

let a =1 
functon fn(){
    console.log(a)
}
fn()
a = 2
Copy the code

Print 1 because fn() is called and a=2 is assigned.

**setTimeout() means as soon as possible, not immediately; ** It is used to call a function or evaluate an expression after a specified number of milliseconds.

let a = 1
function fn=(){
  setTimeout(()=>{
    console.log(a)
  },0)
}

fn()
a=2
Copy the code

Print 2, because setTimeout() causes the function to print the value of A as soon as possible, i.e. the whole thing is executed before printing.

1. For example, the following code:

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

It prints six 6’s

Because setTimeout is an asynchronous task, an operation to this point will be thrown to another task queue by the browser, which will continue to execute the for loop. SetTimeout is executed once each time in the for loop, but the function inside is not executed. Instead, it is placed in the task queue, waiting to be executed. The for loop is executed for 6 times, and then executed in the task queue after the main thread is completed. Now because the for loop is I =6, the output is all 6.

How do you understand asynchrony?

The asynchronous code does not wait for the result of the following code, so the timer is just on, not immediately executing the code inside, waiting for the current running environment code to finish executing the code inside the timer. Conclusion: Asynchrony is code that doesn’t wait for results.

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

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

Since the scope of the let variable can only be in the current function, a new I is generated each time in the for loop. The output I in setTimeout is the new I, and the I is unchanged, so the output is normal.

3, What other method can print 0, 1, 2, 3, 4, 5 besides using for let?

(1) the closure

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

② 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)
}
Copy the code

③ Use const keyword

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

Don’t blow out your inspiration and your imagination; Don’t be a slave to your model. — Vincent Van Gogh