함수 안에 인자로 들어가는 함수, 함수를 순차적으로 실행하고 싶을 때 사용한다.
가장 간단한 예시는 addEventListener, setTimeout들도 기본적으로 내장 함수인데, 이 함수 안에는 인자로 함수가 들어가야 한다.
이 인자에 들어가는 함수들이 콜백함수라고 할 수 있다.
(1) synchronous 콜백함수
순차적으로 실행되는 콜백함수이다.
console.log(1)
function printImmediately(print){
print();
}
printImmediately(()=>console.log('hello'));
console.log(2)
예를들면 위와 같은 예제인데, printImmediately라는 함수는 인자로 콜백함수 하나를 받는다.
위아래로 콘솔로그를 하나씩 설정해두면
콘솔에는 1, hello, 2 순으로 순차적으로 코드가 실행되는 것을 알 수 있다.
(2) asynchronous 콜백함수
비동기적으로 실행되는 콜백함수이다.
console.log(1)
function printWithDelay(print, time){
setTimeout(print, time)
}
printWithDelay(()=>console.log('hello'), 3000);
console.log(2)
위의 예의 결과값은
순차적으로 함수가 실행되지 않고 1과 2 가 찍힌 후에 hello가 찍힌 것을 볼 수 있다.