请使用js实现一个秒表计时器的程序

<!DOCTYPE html>
<html>
<head>
<title>秒表计时器</title>
<style>
#stopwatch {
  font-size: 2em;
  font-family: monospace; /* 使用等宽字体 */
}
</style>
</head>
<body>

<div id="stopwatch">00:00:00</div>
<button id="start">开始</button>
<button id="stop">停止</button>
<button id="reset">重置</button>

<script>
  let startTime = 0;
  let timerInterval;
  let isRunning = false;

  const stopwatch = document.getElementById('stopwatch');
  const startButton = document.getElementById('start');
  const stopButton = document.getElementById('stop');
  const resetButton = document.getElementById('reset');

  function formatTime(milliseconds) {
    const totalSeconds = Math.floor(milliseconds / 1000);
    const seconds = totalSeconds % 60;
    const minutes = Math.floor(totalSeconds / 60) % 60;
    const hours = Math.floor(totalSeconds / 3600);

    return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
  }

  function pad(number) {
    return number < 10 ? `0${number}` : number;
  }

  startButton.addEventListener('click', () => {
    if (!isRunning) {
      startTime = Date.now() - (startTime ? Date.now() - startTime : 0); //  从上次停止的时间继续
      timerInterval = setInterval(() => {
        const elapsedTime = Date.now() - startTime;
        stopwatch.textContent = formatTime(elapsedTime);
      }, 10); //  每10毫秒更新一次,更精确
      isRunning = true;
    }
  });

  stopButton.addEventListener('click', () => {
    if (isRunning) {
      clearInterval(timerInterval);
      isRunning = false;
    }
  });

  resetButton.addEventListener('click', () => {
    clearInterval(timerInterval);
    stopwatch.textContent = "00:00:00";
    startTime = 0;
    isRunning = false;
  });

</script>

</body>
</html>

改进说明:

  • 精度更高: 使用setInterval每10毫秒更新一次显示,使计时更精确。
  • 暂停后继续计时: startTime的处理逻辑更改,现在暂停后再次点击开始可以从暂停的时间点继续计时。
  • 格式化输出: 使用pad()函数确保时间显示始终为两位数,例如00:00:00
  • 代码更清晰: 使用更具描述性的变量名和注释,提高代码可读性。
  • isRunning状态变量: 使用isRunning变量跟踪计时器的运行状态,防止重复启动或停止。

使用方法:

  1. 将代码复制保存为HTML文件 (例如 stopwatch.html)。
  2. 使用浏览器打开该HTML文件。
  3. 点击"开始"按钮开始计时,点击"停止"按钮停止计时,点击"重置"按钮将计时器重置为0。

这个改进版本提供了更精确、更易用的秒表计时器功能。

posted @ 2024-12-08 09:27  王铁柱6  阅读(138)  评论(0)    收藏  举报