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

JavaScript倒计时器多定时器同时运行问题及解决需求

解决倒计时Web应用多定时器同时运行问题

问题说明

当前开发的倒计时Web应用存在以下问题:当已有定时器运行时,点击预设时间按钮或通过自定义输入框设置新时间,旧定时器不会停止,导致新旧定时器同时运行,时间显示混乱。

解决方案代码(修改后的script.js)

let allButtons = document.querySelectorAll(".timer__button");
// 全局变量存储当前定时器ID,用于清除旧定时器
let timerInterval;
// 全局变量存储当前剩余时间
let currentTimeLeft;

// 统一更新倒计时显示的函数
function updateCountdown() {
  if (currentTimeLeft >= 0) {
    const minutes = Math.floor(currentTimeLeft / 60);
    // 补零处理,让秒数始终显示两位
    const seconds = currentTimeLeft % 60 < 10 ? `0${currentTimeLeft % 60}` : currentTimeLeft % 60;
    document.getElementById("display__time-left").textContent = `${minutes}:${seconds}`;
    currentTimeLeft--;
  } else {
    document.getElementById("display__time-left").textContent = "00:00";
    // 倒计时结束后清除定时器
    clearInterval(timerInterval);
  }
}

// 统一计算并显示结束时间的函数
function setEndTime(totalSeconds) {
  const totalMinutes = Math.floor(totalSeconds / 60);
  const now = new Date();
  const currentHours = now.getHours();
  const currentMin = now.getMinutes();
  const endMin = currentMin + totalMinutes;
  
  let endHours = currentHours;
  let finalMin = endMin;
  if (endMin > 59) {
    endHours += Math.floor(endMin / 60);
    finalMin = endMin % 60;
  }
  // 补零处理,让分钟显示两位
  finalMin = finalMin < 10 ? `0${finalMin}` : finalMin;
  document.getElementById('display__end-time').textContent = `Be Back At ${endHours}:${finalMin}`;
}

// 初始化定时器的函数
function initTimer(totalSeconds) {
  // 清除旧定时器
  if (timerInterval) {
    clearInterval(timerInterval);
  }
  currentTimeLeft = totalSeconds;
  // 设置结束时间
  setEndTime(totalSeconds);
  // 立即更新一次显示,避免延迟
  updateCountdown();
  // 启动新定时器
  timerInterval = setInterval(updateCountdown, 1000);
}

// 绑定预设按钮点击事件
allButtons.forEach(button => {
  button.addEventListener("click", function () {
    const time = parseInt(this.value, 10);
    initTimer(time);
  });
});

// 绑定自定义输入框回车事件
document.getElementById("customMin").addEventListener("keypress", function (event) {
  if (event.key === "Enter") {
    event.preventDefault();
    const inputMinutes = parseInt(this.value, 10);
    if (!isNaN(inputMinutes) && inputMinutes > 0) {
      const totalSeconds = inputMinutes * 60;
      initTimer(totalSeconds);
      // 清空输入框
      this.value = "";
    }
  }
});

关键改动说明

  1. 全局定时器ID管理:新增timerInterval变量存储当前定时器的ID,每次启动新定时器前调用clearInterval(timerInterval)清除旧定时器,确保同一时间只有一个定时器运行。
  2. 统一逻辑封装:将倒计时更新、结束时间计算、定时器初始化分别封装为独立函数,避免重复代码,提升可维护性。
  3. 补零处理:对分钟和秒数进行补零,让时间显示格式统一(如5:02而非5:2)。
  4. 输入校验:自定义输入时增加数值校验,确保输入有效正数后才启动定时器,并清空输入框。
  5. 立即更新显示:启动定时器前先调用一次updateCountdown,避免首次显示延迟1秒的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:20:29