UI(Front-End)/javascript 일반
남은 시간, 시간 체크 예제
까오기
2020. 4. 29. 14:37
1. 남은 시간, 시간 체크 예제
본인 확인 등에서 남은 시간을 보여 줄 때 사용하는 예제 입니다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>time Counter 테스트</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
var timeCounter = function(elem, initSecond){
if(!(this instanceof timeCounter)){
return new timeCounter(elem, initSecond);
}
this.elem = elem;
this.initTime = parseInt((new Date()).getTime()/1000)+parseInt(initSecond);
this.si = -1;
}
timeCounter.prototype = {
start: function(){
if(this.si > -1){
return;
}
this.resume();
},
stop: function(){
this.initTime = 0;
this.si = -1;
clearInterval(this.si);
this.print("시간초과");
},
resume: function(){
if(this.si > -1){
return;
}
var _this = this;
_this.si = setInterval(function(){
// 현재시간 구하기
var nowTime = parseInt((new Date()).getTime()/1000);
console.log("nowTime : "+nowTime);
// 초기설정시간과 현재시간 차이 구하기
var tcounter = this.initTime - nowTime;
console.log("tcounter : "+tcounter);
// 분 구하기
var tempMin=Math.floor(tcounter/60);
if(tempMin < 10 ) {
tempMin = '0'+tempMin;
}
// 초 구하기
var tempSec=tcounter%60;
if(tempSec < 10 ) {
tempSec = '0'+tempSec;
}
// 화면에 보여주기
_this.print(tempMin+":"+tempSec);
// 시간 초과면 멈춤.
if(tcounter<0) _this.stop(); // 3분후 완료
}.bind(this), 1000);
},
print: function(elapsed){
$("#"+this.elem).html(elapsed);
},
}
</script>
<script>
$(document).ready(function() {
var timeViewer = timeCounter("timerDiv", 180);
timeViewer.start();
});
</script>
</head>
<body>
남은 시간 : <span id="timerDiv"></span>
</body>
</html>
결과 화면
남은 시간 : 01:22
Mac에서는 setInterval 사용 시 오작동할 수 있습니다.
인스턴스 체크해서 생성을 제한 하는 부분 중요합니다.