You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS时钟格式切换故障求助:12/24小时按钮无法正常切换

解决时钟格式切换失效问题

问题根源

你的代码中,每次点击clock_24()或clock_12()都会创建一个新的setInterval定时器,但从未清除之前的定时器。多个定时器同时运行,会交替修改页面上的时间内容,导致切换后看起来功能失效。另外clock_24使用1ms的定时器间隔,这会严重占用浏览器性能,完全没有必要。

修复方案

我们可以重构代码,用一个全局变量记录当前时钟格式,只保留一个定时器,每次切换格式时更新这个变量即可,避免多个定时器冲突。同时抽离重复的日期格式化逻辑,让代码更简洁。

修复后的完整代码

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Clock Format Switcher</title>
  <!-- font link -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Rokkitt:wght@100&display=swap" rel="stylesheet">

</head>

<body>
  <!-- time and date container  -->
  <div class="t-d-cont">
    <div id="format">
      <h1>24 Hour format</h1>
    </div>
    <div class="redline ">
      <div class="time-box">
        <h1>Current Time: <span id="time"></span></h1>
      </div>
      <div class="date-box">
        <h1> Today's Date: <span id="date"></span></h1>
      </div>
    </div>
    <!-- 24 hour-button -->
    <div class="dropdown">
      <button class="dropbtn-2" onclick="switchFormat('24')">24-hour-format</button>
    </div>
    <!-- 12 hour-button -->
    <div class="dropdown">
      <button class="dropbtn" onclick="switchFormat('12')">12-hour-format</button>
    </div>
  </div>
</body>
</html>

CSS

* {
  margin: 0;
  padding: 0;
}

.t-d-cont {
  background-color: gray;
  margin: 50px;
  padding: 50px;
}

#format {
  border-left: 2px solid rgb(70, 166, 239);
  margin-bottom: 20px;
  padding-left: 20px;
  font-weight: bold;
}

.redline {
  border-left: 2px solid red;
  width: 100%;
  padding-left: 20px;
}

.time-box {
  margin-bottom: 50px;
}

#time {
  font-family: 'Rokkitt', serif;
  font-size: 45px;
}

.date-box {
  margin-bottom: 30px;
}

#date {
  font-family: 'Rokkitt', serif;
  font-size: 45px;
}

.dropbtn {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropbtn-2 {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  margin-left: 15px;
}

JavaScript

// 全局变量:记录当前时钟格式、定时器ID
let currentFormat = '24';
let timerId = null;
// 日期格式化配置
const dateOptions = {
  day: 'numeric',
  month: 'long',
  year: 'numeric'
};

window.onload = () => {
  startClock();
};

// 启动时钟
function startClock() {
  // 先清除之前的定时器,避免多个定时器同时运行
  if (timerId) clearInterval(timerId);
  
  timerId = setInterval(() => {
    const now = new Date();
    // 渲染日期(两种格式共用)
    document.getElementById('date').textContent = now.toLocaleDateString(undefined, dateOptions);
    
    // 根据当前格式渲染时间
    if (currentFormat === '24') {
      const hours = String(now.getHours()).padStart(2, '0');
      const mins = String(now.getMinutes()).padStart(2, '0');
      const secs = String(now.getSeconds()).padStart(2, '0');
      const millis = now.getMilliseconds();
      document.getElementById('time').textContent = `${hours}:${mins}:${secs}:${millis}`;
    } else {
      let hours = now.getHours();
      const session = hours >= 12 ? 'PM' : 'AM';
      hours = hours > 12 ? hours - 12 : hours;
      hours = hours === 0 ? 12 : hours; // 处理0点显示为12点
      hours = String(hours).padStart(2, '0');
      const mins = String(now.getMinutes()).padStart(2, '0');
      const secs = String(now.getSeconds()).padStart(2, '0');
      document.getElementById('time').textContent = `${hours}:${mins}:${secs} ${session}`;
    }
  }, 1000); // 统一用1秒间隔,性能更优
}

// 切换格式
function switchFormat(format) {
  currentFormat = format;
  // 更新格式提示文本
  document.getElementById('format').innerHTML = `<h1>${format === '24' ? '24 Hour format' : '12 Hour format'}</h1>`;
  // 重启时钟(自动清除旧定时器)
  startClock();
}

关键改动说明

  1. 单一定时器管理:用全局变量timerId保存定时器ID,每次启动时钟前先清除旧定时器,避免多个定时器冲突。
  2. 统一格式控制:用currentFormat变量记录当前格式,定时器内根据这个变量渲染对应时间。
  3. 代码复用:抽离日期格式化配置,两种格式共用同一套日期渲染逻辑。
  4. 性能优化:把24小时格式的定时器间隔从1ms改成1000ms,减少不必要的DOM更新。
  5. 修复12小时格式的0点显示:原代码中0点会显示为00:xx:xx AM,修复后显示为12:xx:xx AM,符合常规12小时格式习惯。

内容的提问来源于stack exchange,提问作者Punit Soni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:06:29