横並び複数ストップウォッチ
1
00:00:00
2
00:00:00
3
00:00:00
4
00:00:00
5
00:00:00
仕組み
構造
querySelectorAllとforEach、アロー関数を用いて反復処理をします。
スマートフォンでは解像度の関係上、5つ全て横並びにはなりません。実装する際はCSSを調整してください。
コード
document.querySelectorAll('.stopwatch').forEach(stopwatch => {
let startTime;
let updatedTime;
let difference;
let timerInterval;
let isRunning = false;
const display = stopwatch.querySelector('.display');
const startStopBtn = stopwatch.querySelector('.startStopBtn');
const resetBtn = stopwatch.querySelector('.resetBtn');
function startStopWatch() {
if (!isRunning) {
startTime = new Date().getTime() - (difference || 0);
timerInterval = setInterval(updateDisplay, 1000 / 60);
startStopBtn.textContent = 'Stop';
isRunning = true;
} else {
clearInterval(timerInterval);
startStopBtn.textContent = 'Start';
isRunning = false;
}
}
function resetWatch() {
clearInterval(timerInterval);
isRunning = false;
startStopBtn.textContent = 'Start';
difference = 0;
display.textContent = '00:00:00';
}
function updateDisplay() {
updatedTime = new Date().getTime();
difference = updatedTime - startTime;
let hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((difference % (1000 * 60)) / 1000);
hours = (hours < 10) ? '0' + hours : hours;
minutes = (minutes < 10) ? '0' + minutes : minutes;
seconds = (seconds < 10) ? '0' + seconds : seconds;
display.textContent = `${hours}:${minutes}:${seconds}`;
}
startStopBtn.addEventListener('click', startStopWatch);
resetBtn.addEventListener('click', resetWatch);
});
<div class="stopwatches">
<div class="stopwatch">
<p>1</p>
<div class="display">00:00:00</div>
<button class="startStopBtn">Start</button><button class="resetBtn">Reset</button></div>
<div class="stopwatch">
<p>2</p>
<div class="display">00:00:00</div>
<button class="startStopBtn">Start</button><button class="resetBtn">Reset</button></div>
<div class="stopwatch">
<p>3</p>
<div class="display">00:00:00</div>
<button class="startStopBtn">Start</button><button class="resetBtn">Reset</button></div>
<div class="stopwatch">
<p>4</p>
<div class="display">00:00:00</div>
<button class="startStopBtn">Start</button><button class="resetBtn">Reset</button></div>
<div class="stopwatch">
<p>5</p>
<div class="display">00:00:00</div>
<button class="startStopBtn">Start</button><button class="resetBtn">Reset</button></div>
</div>
<p><script src="script.js"></script></p>
.stopwatch {
display:inline-block;
text-align: center;
border: 1px solid #000;
padding: 4px;
border-radius: 5px;
}
.display {
font-size: 20px;
margin-bottom: 10px;
}
button {
font-size: 12px;
padding: 5px 10px;
margin: 5px;
}