본문 바로가기
Udemy - The web developer camp

Asynchronous JavaScript

by Hanachoi 2022. 12. 10.

# Call stack

  • Call stack is the mecahnism the JS interpreter uses to keep track of its place in a script that calls multiple functions.
  • It is how JS 'knows' what function is currently being run and what functions are called from within tha function, etc
  • 두꺼운 책을 읽을 때, 손가락으로 참조나 주석같은걸 집어가면 지금 어디를 읽고 있는지를 계속 tracking 하는 것
  • Stack is the basic data structure in computer science. It is known as LIFO(Last In First Out ) data structure.
  • How it works 
  • When a script calls a function, the interpreter adds it to the call satack 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 in the last code listing.
  • For example, There is a function that has multiple other funtions in it. isRightTriangle doens't give you the result right away. JS needs to be able to keep tracking the place.
const multiply = (x,y) => x*y;

const sqaure = (x) => multiply(x,x);

const isRightTriangle = (a,b,c) =>{
	return square(a) + square(b) === square(c);
};

isRightTriangle(3,4,5);
  • isRightTriangle(3,4,5) = return square(3) + square(4) === square(5); square(3) is watig for multiply(3,3) and when  multiply(3,3) got the result, 9, multiply(3,3) is removed on call stack. and square(3) returns 9, and now isRightTriangle(3) has the value for the first chunk. And it moves on square(4) and the same process.
  • JavaScript adds those function calls to the call stack and then it removes them whenever a value is returned.
  • Loupe  You can see visualization of the call back function in JS. 
  • The most common tool is Debugger on chrome. You can add some break point, so when something is not going well, you can check what it is going on.

 

 

#Web API and single threaded

  • JS is single threaded which means at any give point in time, that single JS thread is running at most one line of JS code. 
  • It might look taking so much time when you work on large data or weak Internet server. Then what happend between request and writing code for asking something and getting a respond? 
  • Just because it takes some time, it doesn't mean nothing happens. We have a workaround.
  • setTimeout is runnning some code after delay. 
  • In this example, the middle code would be delayed for setTimeout function. But we don't have to wait for 3 seconds for the second console.log, while 3 seconds, the browser does the work. The browser is written by C++, not JS , so it can do what JS can't do. 
console.log('sending request to server!')
setTimeout(()=>{
	console.log('Here is your data frome the server...') //Web API function, so it will let JS know after 3s.
},3000)
console.log('I am at the end of the file!')
  • Browsers come with Web APIs that are able to handle certain tasks in the background(like making 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.

 

# Callback hell

  •  Let's say you want to change HTML background color every 1 second. You cannot work this right away but need to use callback function. 
setTimeOut(()=>{
	document.querySelector.style.backgroundColor = 'red';
},1000) // color turned red in 1 sec.

setTimeOut(()=>{
	document.querySelector.style.backgroundColor = 'orange';
},2000) // if you want the second color, you should count the time and set up

setTimeOut(()=>{
	document.querySelector.style.backgroundColor = 'yellow';
},3000)
  • This way is kinda janky because you need to count all the time it takes.
  • You can also do nest the funcitons.
setTimeOut(()=>{
	document.querySelector.style.backgroundColor = 'red';
    setTimeOut(()=>{
    	document.querySelector.style.backgroundColor = 'orange';
        setTimeOut(()=>{
        	document.querySelector.style.backgroundColor = 'yellow';
        	},1000)
        },1000)
    },1000)
  • You can make a new function 
const delayedColorChange = (newColor,delay,doNext) => {
	setTimeOut(()=>{
    	document.body.style.backgroundColor = newColor ;
        doNext && doNext();
    }delay)
}

delayedColorChange('red',1000, ()=>{
	delayedColorChange('orange',1000,()=>{
    	delayedColorChange('yellow',1000,()=>{
        	delayedColorChange('green',1000)
        })
    })
})
  • This callback pattern is really common. Anytime we have dependent actions where one thing needs to happen and then only after the first thing is finished can the second thing happen, that is where we frequently use callbacks here.
  • Nesting functions is bad, but in real it is really commonly happend. We often have to pass lots of callback that doens't look good and confusing. 
  • This is one of the problem in JS. Having to use callback is somehting we cannot really get around or at least having to provide a mechanism for running code later at some undetermined point in time,  or 10 seocnds form now or zeoro point two seconds, it doens't matter because JS just moves on. So we have to use callback or something to delay running code. 

'Udemy - The web developer camp' 카테고리의 다른 글

JavaScript DOM event  (0) 2022.12.01
JavaScript DOM  (0) 2022.11.17
JavaScript new syntax  (0) 2022.11.12
JavaScript Callback and Array Methods  (0) 2022.10.25
JavaScript function level up  (0) 2022.10.13

댓글