Javascript callback
Javascript 는 synchronous 한다. (동기적입니다.)
hoisting이 된 후 코드가 작성한 순서에 따라 동기적으로 실행된다.
비동기적인(asynchronous) 실행방법
console.log('1');
setTimeout(function () {
console.log('2');
}, 1000);
console.log('3');
// output
//1
//3
//2
첫번째로 console창에 1이 출력되고 두번째로 setTimeout은 Browser API 이므로 Browser에게 1000ms가 지난 후에 callback 함수가 실행되도록 요청하고 응답을 기다리지 않고 바로 세번째로 콘솔에 3을 출력한다. 그러고나면 1초가 지난 후에 setTimeout의 callback 함수가 출력된다.
setTimeout api의 function은 바로 실행되는 것이 아니라 setTimeout 함수 안에 하나의 parameter 인자로 지정한, 우리가 만든 함수를 전달한다.
지금 당장 실행하지 않고 1초가 지난 후에 함수를 실행, 다시 call 해달라고 전달하는 함수를 callback 함수라고 한다.
setTimeout( () => console.log('2'), 1000);
callback을 parameter 인자로 받아서 이를 처리하는 함수를 만들어 볼 것
Synchronous callback
즉각적으로 동기적으로 실행하는 callback
callback을 parameter 인자로 받아서 처리하는 함수
function printImmediately(print) {
print();
} // print 라는 callback을 받아서 바로 실행하는 함수
printImmediately(() => console.log('hello');
Asynchronous callback
언제 실행될지 모르는 비동기적으로 실행되는 callback
function printWithDelay(print, timeout){
setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callback'), 2000);
-----------------------------------------------------------
console.log('1'); //동기
setTimeout( () => console.log('2'), 1000); //비동기
console.log('3'); //동기
printImmediately(() => console.log('hello')); //동기
printWithDelay(() => console.log('async callback'), 2000); //비동기
'JavaScript' 카테고리의 다른 글
JS | async 와 await (0) | 2021.12.29 |
---|---|
JS | Promise ( Producer, Consumer) (0) | 2021.12.28 |
JS | Array (0) | 2021.12.22 |
JS | Script option, Operator, Class and Object (0) | 2021.12.21 |
JS | logical and data type (0) | 2021.12.20 |