Skip to content

Stopwatch Timer

简单 约 20 分钟

你将构建什么

stopwatch displaying elapsed 时间 in MM:SS.ms 格式使用开始, 停止, and Reset buttons. timer 更新每个 10 milliseconds 虽然运行.

学习目标

  • Use setInterval 到更新 timer
  • Track elapsed 时间使用 timestamp
  • 格式 milliseconds 到 MM:SS.ms display
  • 开始, 停止, and reset timer

前置要求

  • 变量 and arithmetic
  • 函数 and 闭包
  • DOM selection and 事件监听器

步骤

  1. 1

    创建 HTML

    创建 display div for timer and three buttons: 开始, 停止, Reset.

    代码
    <div id="display">00:00.0</div>
    <button id="start">Start</button>
    <button id="stop">Stop</button>
    <button id="reset">Reset</button>

    预期结果

    timer display showing 00:00.0 and three buttons appear.

  2. 2

    设置状态 and 格式化

    Declare 变量 for elapsed 时间, interval ID, and 运行状态. 编写格式函数那个 converts milliseconds 到 MM:SS.ms.

    代码
    let elapsed = 0;
    let intervalId = null;
    let running = false;
    
    function format(ms) {
      const totalSec = Math.floor(ms / 1000);
      const min = String(Math.floor(totalSec / 60)).padStart(2, "0");
      const sec = String(totalSec % 60).padStart(2, "0");
      const tenths = Math.floor((ms % 1000) / 100);
      return `${min}:${sec}.${tenths}`;
    }

    预期结果

    格式(65430) 返回 '01:05.4'.

  3. 3

    Wire buttons

    开始: 记录开始时间 and use setInterval 到更新 elapsed 每个 10ms. 停止: 清晰 interval. Reset: 停止 and 设置 elapsed 到 0.

    代码
    const display = document.getElementById("display");
    let startTime = 0;
    
    document.getElementById("start").addEventListener("click", () => {
      if (running) return;
      running = true;
      startTime = Date.now() - elapsed;
      intervalId = setInterval(() => {
        elapsed = Date.now() - startTime;
        display.textContent = format(elapsed);
      }, 10);
    });
    document.getElementById("stop").addEventListener("click", () => {
      running = false;
      clearInterval(intervalId);
    });
    document.getElementById("reset").addEventListener("click", () => {
      running = false;
      clearInterval(intervalId);
      elapsed = 0;
      display.textContent = format(0);
    });

    预期结果

    开始开始 timing, 停止 pauses, Reset 返回到 00:00.0.

  4. 4

    添加输入验证与错误处理

    在用户输入处添加验证:检查空值、非数字、负数等异常情况,用 try/catch 或条件判断给出友好提示。健壮的 JS 程序不会因意外输入而崩溃。

    代码
    function safeParse(value) {
      if (value === null || value === undefined || value === "") {
        throw new Error("Input is empty");
      }
      const num = Number(value);
      if (Number.isNaN(num)) {
        throw new Error(`"${value}" is not a valid number`);
      }
      return num;
    }
    
    try {
      const n = safeParse(userInput);
      process(n);
    } catch (err) {
      console.error(err.message);
    }

    预期结果

    空输入或非数字输入显示错误消息而非崩溃;合法数字正常处理。

  5. 5

    添加事件监听与交互

    为页面元素绑定事件监听器(click、input、keydown 等),让程序响应用户操作。交互性是 JavaScript 在前端的核心价值。

    代码
    const button = document.querySelector("#action-btn");
    const input = document.querySelector("#user-input");
    
    button.addEventListener("click", () => {
      const value = input.value.trim();
      if (!value) return;
      runMainLogic(value);
    });
    
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter") button.click();
    });

    预期结果

    点击按钮或按回车键触发主逻辑;空输入被忽略。

自己动手试试

你学到了什么

你构建 stopwatch using setInterval, Date.现在() for 准确 timing, and clearInterval for pausing — 基本模式 for 任何 timer or polling application.

相关资源

相关课程

  • 函数

    闭包 and timer 回调.

  • DOM

    事件监听器 for button controls.

相关练习

相关速查表

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题