IT/WEB

[JS] 자바스크립트 타이머

오달달씨 2021. 1. 6. 18:03
728x90
반응형

인증번호 폼에 들어가는 타이머를 구현해보자.

 

인증번호 FORM

<body>
	<form name = "login2factor" method="POST" action="/common/login2factor.do">
	인증번호 <input type = "text" name="certification_num" id="certification_num"><span id="timer"></span>
	<input type="submit" value="제출">
	<input type="button" value="재전송">
	</form>
</body>

 

타이머 제한시간 자바스크립트

<script>

// 타이머 구현_daldal
function $ComTimer(){
    //prototype extend
}

$ComTimer.prototype = {
    comSecond : ""
    , fnCallback : function(){}
    , timer : ""
    , domId : ""
    , fnTimer : function(){
        var m = Math.floor(this.comSecond / 60) + "분 " + (this.comSecond % 60) + "초";	// 남은 시간 계산
        this.comSecond--;					// 1초씩 감소
        console.log(m);
        this.domId.innerText = m;
        if (this.comSecond < 0) {			// 시간이 종료 되었으면..
            clearInterval(this.timer);		// 타이머 해제
            alert("인증시간이 초과하였습니다. 다시 인증해주시기 바랍니다.");
            window.close();
            window.opener.location = "/index.do"
        }
    }
    ,fnStop : function(){
        clearInterval(this.timer);
    }
}

var AuthTimer = new $ComTimer()

AuthTimer.comSecond = 180; // 제한 시간

AuthTimer.fnCallback = function(){alert("다시인증을 시도해주세요.")}; // 제한 시간 만료 메세지

AuthTimer.timer =  setInterval(function(){AuthTimer.fnTimer()},1000); 

AuthTimer.domId = document.getElementById("timer"); 

</script>

다음 스크립트를 참고하면 인증번호 입력 폼에 타이머를 구축할 수 있다. 

728x90
반응형