JS function execution timing

JS function execution timing

When to call the function

Every function has its calling time, and the calling time is different, the result will be different naturally.

Here are a few general examples:

let a = 1
function fn(){
    console.log(a)
}
fn()

//1
//   1 
 
let a = 1
function fn(){
    console.log(a)
}
a = 2
fn()

//2
// 2   2 
 
let a = 1
function fn(){
    console.log(a)
}
fn()
a = 2

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

//2
 

The above code has a setTimeoutfunction, it will set a timer, this time is set to 0 means that it will execute immediately after the implementation of the current event queue tasks. Here is the event a = 2to a assignment, so the final printed output is 2.

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

Still a similar example, the result here is that 6 6's will be printed. The reason is the same as above. It setTimeoutwill execute the statement inside itself after the for loop is executed. After the for loop is executed, the value of i is 6, so setTimeoutthe value of i will be printed 6 times, which is 6 Times 6.

The following example will print out 0, 1, 2, 3, 4, and 5:

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

This is why, because in the for loop, the variable i is declared by let and not in the global environment. Here i is only valid in the current round of the loop, and the i in each loop is actually a new variable . And there is another special feature of the for loop, that is, the part where the loop variable is set is a parent scope, and the inside of the loop body is a separate child scope.

This makes the above code similar to:

(let i = 0){
    setTimeout(()=>{console.log(i)},0)
}

(let i = 1){
    setTimeout(()=>{console.log(i)},0)
}

....
 

Therefore, 0, 1, 2, 3, 4, 5 are output.

In addition to the above example, you can also use the const keyword to make the function print 0, 1, 2, 3, 4, and 5:

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

Variables declared with the const keyword must not be changed, and then pass x to the function parameter in setTimeout to print out 0, 1, 2, 3, 4, and 5.

(End)


Reference link:

[1] MDN let statement

[2] Netway ES6 tutorial