- what is call stack?
- The mechanism the JS interpreter uses to keep track of its place in a script that calls multiple functions.
- How js knows what functin is currently being run and what functions are called from within that function.
- How does call stack work?
- When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function
- any functions that are called by that function are added to the call stack further up, and run where their calls are reached
- when the current function is finished, the interpreter takes it off the stack and resumes execution where it left off the last code listing.
- key ided: last in, first out
-
const multiply = (x, y) => x * y; const square = x => multiply(x, x); const isRightTriangle = (a, b, c) => ( square(a) + square(b) === square(c) ) console.log("BEFORE") isRightTriangle(3, 4, 5) console.log("DONEEEE!")
square(a) -> multiply(a,a) ,要想执行square,得先执行multiply,multiply执行完毕之后从栈顶pop出去,然后再执行square(a)。
- WHILE JS is SINGLE THREADED.单线程
- At any given point in time, that single JS thread is running at most one line of JS code.
- What happens when something takes time?
- we have workaround
-
console.log("Sending request to server!") setTimeout(() => { console.log("Here is your data from the server...") }, 3000) console.log("I AM AT THE END OF THE FILE!")
>Sending request to server!
>I AM AT THE END OF THE FILE!
>Here is your data from the server... - Browsera come with WEB APIs that are able to handle certain tasks in the background(like make=ing requests or setTimeout)
- The JS call stack recognizes these Web API functions and passes them off to the browser to take care of
- Once the browser finishes those tasks, they return and are pushed onto the stack as a callback
- call back hell: 不停的嵌套setTimeOut
-
=============== YIKES!!!!!!!!!!! =============== setTimeout(() => { document.body.style.backgroundColor = 'red'; setTimeout(() => { document.body.style.backgroundColor = 'orange'; setTimeout(() => { document.body.style.backgroundColor = 'yellow'; setTimeout(() => { document.body.style.backgroundColor = 'green'; setTimeout(() => { document.body.style.backgroundColor = 'blue'; }, 1000) }, 1000) }, 1000) }, 1000) }, 1000)
代码又丑又麻烦!!!于是,就有了promise这个东西