0%

210125_TIL(타이머)

오늘 배운 것

타이머

JS 엔진은 싱글 스레드이기 때문에 호출 스케쥴링은 브라우저의 역할이다.

setTimeout / clearTimeout

브라우저, NodeJs가 호출하는 호스트 객체이다.

setTimeout은 항상 timerId를 반환한다. 이 함수를 이용해서 다른 반환값을 받는 것은 불가능하기 때문에 콜백함수를 통한 행위를 위해 사용해야한다.

반환하는 timerId는 clearTimeout, clearInterval에 사용된다.

간단한 타이머

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>

<body>
<div class="display">0</div>
<button class="start">start</button>
<button class="stop">stop</button>
<button class="reset">reset</button>
<script>
let num = 0;
let timerId = null;

const $start = document.querySelector(".start");
const $stop = document.querySelector(".stop");
const $reset = document.querySelector(".reset");
const $display = document.querySelector(".display");

$start.onclick = () => {
if (timerId) return;
timerId = setInterval(() => {
num += 1;
$display.textContent = num;
}, 100);
};

$stop.onclick = () => {
clearInterval(timerId);
timerId = null;
};

$reset.onclick = () => {
if (timerId) clearInterval(timerId);
num = 0;
$display.textContent = 0;
timerId = null;
};
</script>
</body>
</html>

비동기 프로그래밍

싱글 스레드인 JS엔진은 콜 스택이 하나뿐이기 때문에 시간이 걸리는 테스크를 처리할 때는 동기 처리방식으로 동작하기 때문에 처리 중인 테스크가 종료될 때까지 블로킹이 발생한다.

위에서 기술한 타이머 함수는 비동기로 동작한다. 커피를 주문하고(비동기 처리되는 함수) 주문벨(프로미스)이 울리기 전까지 다른 행위를 하는 것과 비슷하다.

타이머 함수 외에도 이벤트핸들러 또한 태스크 큐를 통해 실행된다. 때문에 테스크 큐를 이벤트 큐라고도 부른다. 이외에도 자바스크립트에서 호출하는 것이 아닌 브라우저가 호출하는 모든 태스크는 태스크 큐를 통해서 콜 스택에 들어온다.

함수 코드 중에 비동기로 동작하는 부분이 있다면 비동기 함수이다.

Nyong’s GitHub