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

两段近乎相同的JavaScript时钟代码仅一段运行问题求助

问题解决:双时钟同页面仅一个运行的问题

问题根源

  1. 函数名冲突:两段代码里的函数都叫showTime,后定义的函数会覆盖前一个,导致只有最后一个函数在执行。
  2. DOM元素复用:两个时钟都试图更新同一个id="MyClockDisplay"的元素,就算函数不冲突,内容也会被互相覆盖。

修复方案

1. 调整HTML结构

添加两个独立的时钟容器,分别赋予唯一ID:

<div id="WSTClock" class="clock"></div>
<div id="GMTClock" class="clock"></div>

2. 重命名函数并绑定对应DOM元素

把两个时钟函数改成不同的名字,各自更新对应的容器,同时优化时区计算逻辑:

// WST时区时钟函数(小时+1)
function showWSTTime() {
    const date = new Date();
    let h = date.getHours();
    const m = date.getMinutes();
    const session = " WST";

    // 处理0点为12点
    h = h === 0 ? 12 : h;
    // WST时区小时+1,处理23+1=24转为00的情况
    h = (h + 1) % 24;
    // 补零格式化
    h = h < 10 ? "0" + h : h;
    const formattedM = m < 10 ? "0" + m : m;

    const time = `${h}:${formattedM}${session}`;
    document.getElementById("WSTClock").textContent = time;

    setTimeout(showWSTTime, 1000);
}

// GMT时区时钟函数
function showGMTTime() {
    const date = new Date();
    let h = date.getHours();
    const m = date.getMinutes();
    const session = " GMT";

    // 处理0点为12点
    h = h === 0 ? 12 : h;
    // 补零格式化
    h = h < 10 ? "0" + h : h;
    const formattedM = m < 10 ? "0" + m : m;

    const time = `${h}:${formattedM}${session}`;
    document.getElementById("GMTClock").textContent = time;

    setTimeout(showGMTTime, 1000);
}

// 启动两个时钟
showWSTTime();
showGMTTime();

3. 进阶优化:提取公共格式化函数

为避免重复代码,把时间格式化逻辑抽成公共函数:

// 公共时间格式化函数
function formatTime(hours, minutes, session) {
    let h = hours;
    // 处理0点为12点
    h = h === 0 ? 12 : h;
    // 补零
    h = h < 10 ? "0" + h : h;
    const m = minutes < 10 ? "0" + minutes : minutes;
    return `${h}:${m}${session}`;
}

function showWSTTime() {
    const date = new Date();
    const h = (date.getHours() + 1) % 24;
    const m = date.getMinutes();
    const time = formatTime(h, m, " WST");
    document.getElementById("WSTClock").textContent = time;
    setTimeout(showWSTTime, 1000);
}

function showGMTTime() {
    const date = new Date();
    const h = date.getHours();
    const m = date.getMinutes();
    const time = formatTime(h, m, " GMT");
    document.getElementById("GMTClock").textContent = time;
    setTimeout(showGMTTime, 1000);
}

showWSTTime();
showGMTTime();

额外说明

  • 原代码里innerText和textContent重复设置,保留一个textContent即可,兼容性更好。
  • WST时区小时+1时,用(h + 1) % 24可处理23+1=24的情况,转为00符合24小时制逻辑。

内容的提问来源于stack exchange,提问作者Tom Webber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:15:44