앞서 고차함수에서 간단히 동기와 비동기에 대해 설명했다 이번시간에는 좀 더 자세히 자바스크립트에서 이러한 특성이 어떻게 나타나고, 이용하는지 알아보자
setTimeout(callback, millisecond)
일정 시간 후에 함수를 실행
setTimeout(function () {
console.log('1초 후 실행');
}, 1000);
// 1초 뒤에 콘솔 출력
clearTimeout(timerId)
setTimeout 타이머를 종료
const timer = setTimeout(function () {
console.log('10초 후 실행');
}, 10000);
clearTimeout(timer);
// setTimeout이 종료됨.
setInterval(callback, millisecond)
일정 시간의 간격을 가지고 함수를 반복적으로 실행
setInterval(function () {
console.log('1초마다 실행');
}, 1000);
// 1초마다 실행
// 1초마다 실행
// 1초마다 실행
// ...
clearInterval(timerId)
setInterval 타이머를 종료
const timer = setInterval(function () {
console.log('1초마다 실행');
}, 1000);
clearInterval(timer);
// setInterval이 종료
콜백함수를 통해 비동기 코드의 순서를 제어할 수 있다
const printAll = () => {
printString('A', () => {
printString('B', () => {
printString('C', () => {});
});
});
};
printAll(); // A B C
콜백 지옥 Callback Hell
const printAll = () => { printString('A', () => { printString('B', () => { printString('C', () => { printString('D', () => { printString('E', () => { printString('F', () => { printString('G', () => { printString('H', () => { ... }); }); }); }); }); }); }); }; printAll();
콜백함수는 코드가 길어질수록 복잡해지고 가독성이 낮아지는 단점이 있다