Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- for in
- flex
- properties
- justify-content
- 함수표현식
- 화살표함수
- 조건문
- for
- 변수
- if else
- boolean
- javascript
- for of
- flex-wrap
- 비교연산자
- 프론트엔드
- typeof
- ELSE
- frontend
- 반복문
- 함수
- 함수선언식
- 논리연산자
- flex-direction
- Methods
- 속성
- align-content
- 기초
- 문자열
- 타입
Archives
- Today
- Total
하얀 코딩
[JavaScript - 20] 타이머 API 본문
JavaScript에서 비동기를 경험하게 되는 첫번째 단계는 타이머와 관련된 API입니다.
해당 API는 브라우저에서 제공하는 Web API이며 비동기로 작동하도록 구성되어 있습니다.
setTimeout(callback, millisecond)
일정 시간 후에 함수를 실행
setTimeout(function () {
console.log('1초 후 실행');
}, 1000);
1. callback
실행할 콜백 함수
2. millisecond (1000ms = 1s)
콜백 함수 실행 전 기다려야 할 시간
3. return
임의의 타이머 ID. index 번호로 1번 부터 출력 된다.
clearTimeout(timerId)
setTimeout 타이머를 종료
const timer = setTimeout(function () {
console.log('10초 후 실행');
}, 10000);
clearTimeout(timer);
// setTimeout이 종료됨.
1. timerId
타이머 ID
2. return
없음.
setInterval(callback, millisecond)
일정 시간의 간격을 가지고 함수를 반복적으로 실행
setInterval(function () {
console.log('1초마다 실행');
}, 1000);
1. callback
실행할 콜백 함수
2. millisecond (1000ms = 1s)
반복적으로 함수를 실행시키기 위한 시간 간격
3. return
임의의 타이머 ID. index 번호로 1번 부터 출력 된다.
clearTimeout(timerId)
setInterval 타이머를 종료
const timer = setInterval(function () {
console.log('1초마다 실행');
}, 1000);
clearInterval(timer);
// setInterval이 종료됨.
1. timerId
타이머 ID
2. return
없음.
비동기 코드는 코드가 작성된 순서대로 작동되는 것이 아니라 동작이 완료되는 순서대로 작동하게 됩니다.
즉, 코드의 순서를 예측할 수 없습니다. 아래의 코드를 살펴보면서 이해해보세요.
const printString = (string) => {
setTimeout(function () {
console.log(string);
}, Math.floor(Math.random() * 100) + 1);
};
const printAll = () => {
printString('A');
printString('B');
printString('C');
};
printAll(); // ABC는 랜덤으로 출력이 된다.
비동기를 동기화 한다?
비동기로 작동하는 코드를 제어할 수 있는 방법에 대해 잘 알고 있어야 합니다.
여러 방법 중 하나는 Callback 함수를 활용하는 방법입니다.
Callback 함수를 통해 비동기 코드의 순서를 제어할 수 있습니다. 즉, 비동기를 동기화할 수 있다는 의미입니다.
const printString = (string, callback) => {
setTimeout(function () {
console.log(string);
callback();
}, Math.floor(Math.random() * 100) + 1);
};
const printAll = () => {
printString('A', () => {
printString('B', () => {
printString('C', () => {});
});
});
};
printAll();
// A
// B
// C
'JavaScript' 카테고리의 다른 글
[JavaScript - 22] Promise.prototype.then(), catch(), finally() (0) | 2023.01.12 |
---|---|
[JavaScript - 21] Promise (0) | 2023.01.11 |
[JavaScript - 19] 동기 / 비동기 (0) | 2023.01.11 |
[JavaScript - 17] (내장) 고차 함수 (0) | 2023.01.11 |
[JavaScript - 16] 고차 함수 / 콜백 함수 (0) | 2023.01.11 |