After learning JS functions today, I will summarize the execution time of JS functions, and give some examples to understand the call stack
This article is their own summary, if there is a problem please provide help, thank you!!
How is the JS function called?
Let’s define a function and call that function
Function fn(){console.log(' I was called ')}fn()console.log(' after calling fn, execute me ')Copy the code
The above code simply calls the function fn
Print out ‘I’m called,’ and then print out ‘After calling fn, execute me.’
In the JS engine, how does this code know that I called fn first?
Now that I know, how do I find the code after FN?
Here we use the call stack in the JS engine
- In carrying out the
fn()
When the JS engine records the location, we assume asone
- And then we did
Push and press the stack
The operation of the - So that ourThe call stackIt’s in the book
fn()
- Then enter the fn function, and the JS engine records
Console. log(' I've been called ')
The position of, let’s assumetwo
- Continue to
Push and press the stack
Console. log(' I've been called ')
After pressing the stack, it was popped and printed- And it pops up
Fn function
When the function is not given a return, the defaultreturn undefined
- Then the JS engine records
Console. log(' after calling fn, execute me ')
The position of, let’s assumethree
- Continue to
Push and press the stack
- JS engine, found nothing, started to execute the stack
- The stack is pushed first and then removed
- So this is the call stack, and it’s done in sequence, and every time you bounce one, you end up on the stack
- All the way down the stack
- This is the
The execution timing of the JS function
The picture below, combined with the text above, is better understood
Explain why the following code prints six sixes
In the following code, why does the following code print six sixes?
let i = 0 for(i = 0; i<6; I ++){setTimeout(()=>{console.log(I)},0)} It's executing when it's bouncing but when it's executing it's for when it's ending the loop and then I is 6, so it's executing it every timeCopy the code
Write a way to let the above code print 0, 1, 2, 3, 4, 5
for(let i = 0; i<6; I ++){setTimeout(()=>{console.log(I)},0)} The use of let will result in block-level scope where each stack of setTimeout's I is independentCopy the code
What other way to print out 0, 1, 2, 3, 4, 5 besides using the for let tie-in
SetTimeout is the third argument
let i = 0
for(i = 0; i<6; i++){
setTimeout((j)=>{
console.log(j)
},0,i)
}
Copy the code
Closure + Executes the function immediately
let i = 0 for(i = 0; i<6; i++){ ! function (){ setTimeout((j)=>{ console.log(j) },0,i) }() }Copy the code
Use the const keyword
let i
for(i = 0; i<6; i++){
const x = i
setTimeout(()=>{
console.log(x)
})
}
Copy the code
Conclusion:
-
JS function execution, need to refer to the call stack
-
The call stack is based on the JS engine
-
The rule is push first, then out
Thanks to Mr. Awkward for asking this article! ! !