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

JavaScript控制台秒表:重置后如何重新启动?

控制台秒表重置重启功能修复方案

问题核心

你当前代码的关键问题有两个:

  1. 输入分支逻辑覆盖:input === 'i'的两个判断顺序错误,导致重置后按i启动的分支永远无法触发;
  2. 计时逻辑精度缺陷:依赖全局变量逐秒累加的方式容易产生误差,重置后的状态流转也未理顺。

修复代码与说明

1. 调整输入处理逻辑

合并重复的启动判断,理顺重置→启动的状态流转:

function run() {
    const rl = readline.createInterface({
        input: process.stdin
    });

    rl.on('line', (input) => {
        const cmd = input.toLowerCase();
        if (cmd === 'i') {
            if (!running) {
                // 重置后暂停状态下,先初始化所有变量
                if (restarted && paused) { 
                    seconds = 0;
                    minutes = 0;
                    hours = 0;
                    hundredths = 0;
                    laps = [];
                    restarted = false;
                    paused = false;
                }
                startStopwatch();
            } else if (paused) {
                // 运行中暂停时,按i恢复计时
                paused = false;
                console.log('Stopwatch resumed.');
            }
        } else if (cmd === 'p' && running) {
            paused = !paused;
            console.log(paused ? 'Stopwatch is paused.' : 'Stopwatch resumed.');
        } else if (cmd === 'd' && running) {
            running = false;
            rl.close();
            console.log('Stopwatch has been stopped.');
        } else if (cmd === 'l' && running && !paused) {
            recordLaps();
        } else if (cmd === 'v' && paused) {
            showLaps();
        } else if (cmd === 'r' && paused) {
            // 重置时直接初始化变量,标记重置状态
            seconds = 0;
            minutes = 0;
            hours = 0;
            hundredths = 0;
            laps = [];
            restarted = true;
            console.log('Stopwatch has been reset.');
            await clearConsole();
            console.log('00:00:00.00');
        }
    });
}

2. 优化秒表计时逻辑

改为基于总流逝时间计算,避免逐秒累加的误差,同时确保重置后从零开始:

async function Stopwatch() {
    let startTime = Date.now();

    while (running) {
        if (!paused) {
            const currentTime = Date.now();
            const totalElapsed = currentTime - startTime;
            
            // 直接从总流逝时间计算各单位,替代逐秒累加
            hundredths = Math.floor((totalElapsed % 1000) / 10);
            seconds = Math.floor((totalElapsed / 1000) % 60);
            minutes = Math.floor((totalElapsed / (1000 * 60)) % 60);
            hours = Math.floor(totalElapsed / (1000 * 60 * 60));

            const Hours = getTimeFormat(hours),
                  Minutes = getTimeFormat(minutes),
                  Seconds = getTimeFormat(seconds),
                  Hundredths = getTimeFormat(hundredths); 
                    
            await clearConsole();
            console.log(`${Hours}:${Minutes}:${Seconds}.${Hundredths}`);
        }
        await sleep(10); // 调整刷新间隔,平衡精度与性能
    }
}

async function startStopwatch() {
    running = true;
    paused = false; // 启动时强制取消暂停
    await clearConsole();
    await Stopwatch();
}

3. 补充全局变量与辅助函数(确保代码完整)

// 全局状态与时间变量
let running = false;
let paused = false;
let restarted = false;
let seconds = 0;
let minutes = 0;
let hours = 0;
let hundredths = 0;
let laps = [];

// 时间格式化辅助函数
function getTimeFormat(num) {
    return num.toString().padStart(2, '0');
}

// 清屏函数
async function clearConsole() {
    console.clear();
}

// 休眠函数
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// 记录lap函数
function recordLaps() {
    const lapTime = `${getTimeFormat(hours)}:${getTimeFormat(minutes)}:${getTimeFormat(seconds)}.${getTimeFormat(hundredths)}`;
    laps.push(lapTime);
    console.log(`Lap ${laps.length} recorded: ${lapTime}`);
}

// 查看lap函数
function showLaps() {
    console.log('--- Laps ---');
    laps.forEach((lap, idx) => {
        console.log(`Lap ${idx+1}: ${lap}`);
    });
    console.log('------------');
}

功能使用说明

  • 按i:未运行时启动秒表;运行中暂停时恢复计时;重置后暂停时从零启动
  • 按p:运行中切换暂停/恢复状态
  • 按r:暂停时重置秒表到0,保持暂停状态
  • 按l:运行且未暂停时记录当前 lap
  • 按v:暂停时查看所有已记录的 lap
  • 按d:停止秒表并关闭输入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:49:51