Count Down Timer
by yshrkn
HTML
<time id="timer">00:00</time>
<div class="control">
<input type="text" id="timer-seconds-input" value="5" maxlength="2">
<button class="btn" id="start-timer-btn">Start</button>
</div>
CSS
#timer {
font-size: 128px;
font-weight: bold;
background-color: #333;
color: white;
padding: 15px;
border: 5px solid black;
display: inline-block;
font-family: Helvetica;
}
.control {
display: flex;
margin: 10px 0;
}
#timer-seconds-input {
width: 3em;
text-align: right;
margin-right: 5px;
}
#start-timer-btn {
cursor: pointer;
}
JavaScript
/*
* 以下の要件を満たすカウントダウンタイマーアプリを作成してください。
*
* 1. #start-timer-btn をクリックすると、カウントダウンを開始します。
* 2. カウントダウンの開始秒数は #timer-seconds-input の入力値とします。
* 3. カウントダウン開始と同時に、#start-timer-btn のラベルテキストは、Pauseに切り替えます。
* 4. カウントダウンの更新は1/100秒毎に実行します。
* 5. [Pause] の状態のボタンをクリックすると、ラベルは [Start] に戻り、カウントダウンは一時停止します。
* 6. カウントダウン終了時に、#start-timer-btn のテキストラベルを再度 [Start] に切り替えます。
*/
var timerDisplay = document.getElementById('timer');
var timerStartBtn = document.getElementById('start-timer-btn');
var isCounting = false;
var isPausing = false;
var remainOfSeconds = 0;
var countTimer;
timerStartBtn.addEventListener("click", function(e) {
if (isCounting) {
pauseTimer();
if (isPausing) {
countTimer = setInterval(countDown, 10);
timerStartBtn.textContent = "Pause";
isPausing = false;
} else {
isPausing = true;
pauseTimer();
}
} else {
remainOfSeconds = Number(document.getElementById('timer-seconds-input').value, 10) * 100;
countTimer = setInterval(countDown, 10);
timerStartBtn.textContent = "Pause";
isCounting = true;
}
});
function formatNum(num, min) {
var num_str = num.toString();
while (num_str.length < min) {
num_str = '0' + num_str;
}
return num_str;
}
function pauseTimer() {
timerStartBtn.textContent = "Start";
clearInterval(countTimer);
}
function countDown() {
remainOfSeconds -= 1;
var remained = formatNum(remainOfSeconds.toString(), 4);
var int = formatNum(remained.substr(0, 2), 2);
var decimal = formatNum(remained.substr(2, 2), 2);
if (remainOfSeconds <= 0) {
pauseTimer();
timerDisplay.textContent = "00:00";
isCounting = false;
}
timerDisplay.textContent = int + ":" + decimal;
}