티스토리 뷰
startTimer : function(){
if(!this.isPending) {
this.timerId = setInterval(() => {
this.currentSec+=1;
if(this.currentSec >= 60) {
this.currentMin+=1;
this.currentSec = 0;
}
document.querySelector('#min').textContent = `${this.currentMin < 10 ? `0${this.currentMin}` : `${this.currentMin}`}`;
document.querySelector('#sec').textContent = `${this.currentSec < 10 ? `0${this.currentSec}` : `${this.currentSec}`}`;
}, 1000)
}
},
pauseTimer : function(){
clearInterval(this.timerId);
this.isPending = true;
},
1초마다 시간으 랜더링하는 스톱워치를 다음과 같은 소스를 통해 구현하였다.
하지만 시간의 흐름을 제어하는 변수인 isPending이 있음에도 setInterval()를 사용함으로써, 시간을 멈추는 버튼을 클릭하였을 경우
별도로 timerId를 선언하여 주고 이를 통해 clearInterval()로 해제하는 과정이 불필요하게 추가되었다.
시간을 제어하는 변수가 두 개가 있을 필요는 없기 때문에 기존의 주어진 isPending 변수를 이용한 방식으로 구현해보고자 한다.
Refactoring_SetTimeout으로 재귀 호출
startTimer : function(){
if(!this.isPending){ //재귀반복 시 isPending이 true일 경우에는 해당문을 실행 하지 않음
this.currentSec+=1;
if(this.currentSec==60){
this.currentSec=0;
this.currentMin+=1;
}
document.querySelector('#min').innerHTML = ('0' + this.currentMin).slice(-2);
document.querySelector('#sec').innerHTML = ('0' + this.currentSec).slice(-2);
setTimeout("Timer.startTimer()", 1000); //1초 뒤에 다시 startTimer 매서드 호출
}
},
pauseTimer : function(){
this.isPending = true;
},
}
document.querySelector('#start').addEventListener('click' , function(){
if(Timer.isPending){ //스톱워치가 작동하는 경우에는 중복으로 실행되는 것을 방지
Timer.isPending = false;
Timer.startTimer();
}
});
'JS' 카테고리의 다른 글
클래스나 아이디 값이 없는 Element 가져올 때 문제 (0) | 2021.07.22 |
---|---|
getPropertyValue의 반환값 (0) | 2021.07.20 |
pipe operator를 통해 오퍼레이터 처리 (0) | 2021.07.17 |
RxJS debounceTime operator를 통해 Event request 줄이기 (0) | 2021.07.17 |
textContent의 공백 문제 (0) | 2021.07.16 |
댓글