JS functions run at different times and have different results

Synchronization task:

You don’t do the last thing until the last thing is done, you don’t do the next thing until the last thing is done most of the time in JS is synchronous programming

Case a

Let a = 1 function fn(){console.log(a)} //a does not exist because fn is not executedCopy the code

Nothing is printed here because the function is declared but not executed

Case 2

let a = 1 
function fn(){
     console.log(a) 
} 
fn() // 1
Copy the code

This will print a, because we declared a at the beginning, and the value of a is 1, and then we call fn and print a.

Asynchronous tasks:

We plan to do something, but instead of doing it right now, we need to wait for a certain amount of time. In this case, we will not wait for it to do, but continue to do the following operation.

Case a

Let a= 1 function fn() {setTimeout(()=>{console.log(a)},0)} fn() {console.log(a)},0) = 2Copy the code

SetTimeout will wait until the current code is executed, i.e. after let a= 1, fn(), a=2, console.log(a) is executed

Case 2

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

SetTimeout is executed every time the for loop is executed. SetTimeout waits until the current code completes its for loop and then executes console.log(I), which is already 6

Case 3

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

Add let to the for loop I. A hidden scope is created. Each time the for loop is executed, JS keeps the initial value of I and then redeclares it to be executed once. The equivalent of

(let i = 0) { 
    setTimeout(()=>{ 
        console.log(i) 
        },0) 
} 
(let i = 1) { 
    setTimeout(()=>{ 
        console.log(i) 
        },0) 
} 
(let i = 2) { 
    setTimeout(()=>{ 
        console.log(i) 
        },0) 
}
(let i = 3) { 
    setTimeout(()=>{ 
        console.log(i) 
        },0) 
} 
(let i = 4) { 
    setTimeout(()=>{ 
        console.log(i) 
        },0) 
} 
(let i = 5) { 
    setTimeout(()=>{ 
        console.log(i) 
        },0) 
};

Copy the code

Popular understanding of setitmeout

Play a game and immediately remove the enemy crystal, when someone calls you, you say immediately (corresponding to setTimeout(function, 0)), but in fact, you will finish the game and then go.

Four cases

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

Var does not work with setTimeout