当单击停止按钮时无法使秒表停止,可能涉及以下几个方面的基础概念和解决方案:
setTimeout
和 setInterval
,用于定时执行某些操作。以下是一个简单的示例代码,展示如何实现一个可停止的秒表:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>秒表示例</title>
</head>
<body>
<div id="display">0.00</div>
<button id="startStopBtn">开始</button>
<script>
let startTime;
let elapsedTime = 0;
let timerInterval;
const display = document.getElementById('display');
const startStopBtn = document.getElementById('startStopBtn');
function startTimer() {
startTime = Date.now() - elapsedTime;
timerInterval = setInterval(updateDisplay, 10);
startStopBtn.textContent = '停止';
}
function stopTimer() {
clearInterval(timerInterval);
startStopBtn.textContent = '开始';
}
function updateDisplay() {
elapsedTime = Date.now() - startTime;
display.textContent = (elapsedTime / 1000).toFixed(2);
}
startStopBtn.addEventListener('click', () => {
if (startStopBtn.textContent === '开始') {
startTimer();
} else {
stopTimer();
}
});
</script>
</body>
</html>
display
元素用于显示秒表时间。startStopBtn
按钮用于开始和停止秒表。startTime
记录秒表开始的时间。elapsedTime
记录已经过去的时间。timerInterval
是一个定时器 ID,用于存储 setInterval
的返回值。startTimer
函数用于开始计时,并更新按钮文本为“停止”。stopTimer
函数用于停止计时,并更新按钮文本为“开始”。updateDisplay
函数用于更新显示的时间。通过上述代码和解释,可以解决单击停止按钮时无法使秒表停止的问题,并理解其背后的基础概念和应用场景。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云