티스토리 뷰

JS

setTimeout으로 setInterval 구현

choi95 2021. 7. 18. 15:28
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();
        }
    });

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
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
글 보관함