以下是一个简易的计时器和时钟的实现示例:

计时器:

<!DOCTYPE html>
<html>
<body>

<h2>计时器</h2>

<button onclick="startTimer()">开始</button>
<button onclick="stopTimer()">停止</button>
<button onclick="resetTimer()">重置</button>

<p id="timer">00:00:00</p>

<script>
var timer;
var seconds = 0, minutes = 0, hours = 0;

function startTimer() {
  timer = setInterval(updateTimer, 1000);
}

function updateTimer() {
  seconds++;
  if (seconds == 60) {
    seconds = 0;
    minutes++;
    if (minutes == 60) {
      minutes = 0;
      hours++;
    }
  }

  var timeString = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" +
                   (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" +
                   (seconds > 9 ? seconds : "0" + seconds);
  document.getElementById("timer").textContent = timeString;
}

function stopTimer() {
  clearInterval(timer);
}

function resetTimer() {
  clearInterval(timer);
  seconds = 0;
  minutes = 0;
  hours = 0;
  document.getElementById("timer").textContent = "00:00:00";
}
</script>

</body>
</html>

时钟:

<!DOCTYPE html>
<html>
<body>

<h2>时钟</h2>

<p id="clock"></p>

<script>
function updateClock() {
  var now = new Date();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();

  var timeString = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" +
                   (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" +
                   (seconds > 9 ? seconds : "0" + seconds);
  document.getElementById("clock").textContent = timeString;
}

setInterval(updateClock, 1000);
</script>

</body>
</html>

你可以将上述代码保存为html文件并在浏览器中运行,即可看到计时器和时钟效果

利用js实现一个简易计时器和时钟

原文地址: http://www.cveoy.top/t/topic/iIlJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录