하얀 코딩

[JavaScript - 20] 타이머 API 본문

JavaScript

[JavaScript - 20] 타이머 API

whitecoding 2023. 1. 11. 22:39

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