You need to enable JavaScript to run this app. 如何通过原生JS实现秒表同一按钮点击切换启动与暂停?
优惠活动
大模型
产品
解决方案
定价
更多

如何通过原生JS实现秒表同一按钮点击切换启动与暂停?

问题根源

你写的START按钮点击逻辑没有加状态判断,不管当前计时器是不是在运行,每次点按钮都会直接新开一个1秒触发的计时任务:既不会在第二次点击时停掉之前的计时器,也不会同步切换按钮文本,自然实现不了启停切换的循环效果。

修改思路

通过startStopwatch这个变量判断当前计时状态,每次点击按钮走对应分支逻辑:

  • 如果startStopwatch为null(无正在运行的计时器):启动计时任务,把按钮文本改成STOP
  • 如果startStopwatch存储了有效的计时器ID(计时正在运行):清除当前计时任务,把状态标识重置为null,按钮文本切回START

顺便修复两个原有代码的细节问题:

  • 解决连续点击START按钮会生成多个并行计时实例、导致时间跳变的问题
  • 优化RESET按钮的逻辑:触发重置时同步清理残留的计时器引用、复位按钮文本,避免状态不一致
改造后完整代码
let seconds = '00';
let minutes = '00';
let hours = '00';
let startStopwatch = null;

function startTimer() {
  seconds = Number(seconds) + 1;
  if (seconds < 10) {
    seconds = '0' + seconds;
  } else if (seconds === 60) {
    seconds = '00';
    minutes = Number(minutes) + 1;
  }

  if (typeof minutes === 'number' && Number(minutes) < 10) {
    minutes = '0' + minutes;
  }

  if (Number(minutes) === 60) {
    minutes = '00';
    hours = Number(hours) + 1;
  }

  if (typeof hours === 'number' && Number(hours) < 10) {
    hours = '0' + hours;
  }

  document.querySelector('.numbers').textContent = `${hours}:${minutes}:${seconds}`;
}

document.querySelector('.start').addEventListener('click', function () {
  if (startStopwatch) {
    clearInterval(startStopwatch);
    startStopwatch = null;
    this.textContent = 'START';
  } else {
    startStopwatch = setInterval(startTimer, 1000);
    this.textContent = 'STOP';
  }
});

document.querySelector('.reset').addEventListener('click', function () {
  if (startStopwatch) {
    clearInterval(startStopwatch);
    startStopwatch = null;
  }
  seconds = '00';
  minutes = '00';
  hours = '00';
  document.querySelector('.numbers').textContent = `${hours}:${minutes}:${seconds}`;
  document.querySelector('.start').textContent = 'START';
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 05:15:04