반응형
javaScript
- is synchronous(동기)
- execute the code block by orger after hoisting
hoisting : var, function declaration이 해당 범위의 최상위로 올려지는 것
동기(Synchronized)
동기란 짜여진 코드 순서대로 실행되는 것을 의미한다.
즉, 제일 위의 코드가 제일 먼저 실행되고 실행이 완료되면 그 다음 순서의 코드가 실행된다.
비동기(Asynchronized)
동기적 실행이 하나의 흐름안에서 실행이 된다면 비동기적 실행은 이 흐름이 나뉘어 져서 두개이상의 함수가 동시에 동작한다.
아래의 코드를 예를 들 수 있다.
console.log('1')
//browser API
setTimeout(() => console.log('2'), 1000);
console.log('3')
순서는 1 - 2 - 3이지만 setTimeout()라는 브라우저 API에 의해 1 - 3 -2 순서로 콘솔에 출력된다.
Synchronouse Callback vs Asynchronouse Callback
console.log('1')
setTimeout(() => console.log('2'), 1000);
console.log('3')
//Synchronouse Callback
function printImmediately(print){
print();
}
printImmediately(() => console.log("hi"));
//Asynchronouse Callback
function printWithDelay(print, timeout){
setTimeout(print,timeout);
}
printWithDelay(() => console.log('async callback'), 2000);
위의 코드가 hoisting 후 실행되는 순서대로 배치하면 아래와 같이 된다
//Synchronouse Callback
function printImmediately(print){
print();
}
//Asynchronouse Callback
function printWithDelay(print, timeout){
setTimeout(print,timeout);
}
console.log('1')
console.log('3')
printImmediately(() => console.log("hi"));
setTimeout(() => console.log('2'), 1000);
printWithDelay(() => console.log('async callback'), 2000);
반응형
'JavaScript' 카테고리의 다른 글
배열을 문자열로 - join() 함수 (0) | 2022.08.26 |
---|---|
Object.keys() (0) | 2022.08.20 |
배열/함수들 (0) | 2022.06.24 |
변수 - var, let, const (0) | 2022.06.24 |