Skip to content

Instantly share code, notes, and snippets.

@donguri9
Created December 4, 2017 12:16
Show Gist options
  • Save donguri9/f8627b0953da401ff60214a9b44226ce to your computer and use it in GitHub Desktop.
Save donguri9/f8627b0953da401ff60214a9b44226ce to your computer and use it in GitHub Desktop.
count down timer
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="timer">00:00.000</div>
<div class="contorol">
<button id = "min">Min</button>
<button id = "sec">sec</button>
<button id = "reset">reset</button>
<button id = "start">start</button>
</div>
<script>
(function(){
'use strict';
var timer = document.getElementById('timer');
var min = document.getElementById('min');
var sec = document.getElementById('sec');
var rset = document.getElementById('reset');
var start = document.getElementById('start');
var startTime;
var timeLeft;
// var timeCountDown = 4 * 1000;
var timeCountDown = 0;
var timerId;
var isRunning = false;
var timerString;
function upDateTimer(t){
var d = new Date(t);
var m = d.getMinutes();
var s = d.getSeconds();
var ms = d.getMilliseconds();
m = ('0' + m).slice(-2);
s = ('0' + s).slice(-2);
ms = ('00' + ms).slice(-3);
timerString = m + ":" + s + "." + ms;
timer.textContent = timerString;
document.title = timerString;
}
function countDown(){
timerId = setTimeout(function(){
timeLeft = timeCountDown - (Date.now() - startTime);
if (timeLeft < 0 ){
isRunning = false;
start.textContent = 'start';
clearTimeout(timerId);
timeLeft = 0;
upDateTimer(timeLeft);
return
}
upDateTimer(timeLeft);
countDown();
},10)
};
start.addEventListener('click',function(){
if (isRunning == false){
isRunning = true;
start.textContent = 'stop'
startTime = Date.now();
countDown();
}else{
isRunning = false;
start.textContent = 'start';
timeCountDown = timeLeft;
clearTimeout(timerId);
}
})
min.addEventListener('click',function(){
if (isRunning == true){
return;
}
timeCountDown += 60 * 1000;
upDateTimer(timeCountDown)
})
sec.addEventListener('click',function(){
if (isRunning == true){
return;
}
timeCountDown += 1000;
upDateTimer(timeCountDown)
})
reset.addEventListener('click',function(){
timeCountDown = 0;
upDateTimer(timeCountDown)
})
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment