秒表重新计时后如何重新启动?

问题描述 投票:0回答:1

所以我才刚刚开始学习 JavaScript,喜欢它的语法和逻辑,因此我仍然没有在网页上实现任何内容,只是在使用 JS 进行任何 Web 开发之前使用控制台。

我想实现这个功能,一个重新启动功能,您可以在重新启动秒表后再次启动秒表,但我还没有弄清楚如何做到这一点

这是 run() 函数,其中包含控制秒表所需的所有输入的逻辑(例如开始键、暂停/恢复键、停止键和重启键:

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

    rl.on('line', (input) => {
        if (input.toLowerCase() === 'i') {
            if (!running) {
                if (restarted && paused) { 
                    seconds = 0;
                    minutes = 0;
                    hours = 0;
                    hundredths = 0;
                    laps = [];
                    restarted = false;
                    // restartTime = Date.now(); not sure if this even works as I expect it to.
                }
                startStopwatch();
            }
        } else if (input.toLowerCase() === 'p' && running) {
            paused = !paused;
            console.log('Stopwatch is paused.');
        } else if (input.toLowerCase() === 'd' && running) {
            running = false;
            rl.close();
            console.log('Stopwatch has been stopped.');
        } else if (input.toLowerCase() === 'l' && running && !paused) {
            recordLaps();
        } else if (input.toLowerCase() === 'v' && paused) {
            showLaps();
        } else if (input.toLowerCase() === 'r' && paused) {
            restarted = true;
            console.log('Stopwatch has been restarted.');
        } else if (input.toLowerCase() === 'i' && restarted && paused) {
            startStopwatch();
        }
    });
}
javascript stopwatch console-input
1个回答
0
投票

这是 Stopwatch() 函数的样子,我还展示了 startStopwatch() 函数。

async function Stopwatch() {
    let startTime = Date.now();
    
    while (running) {
        if (!paused) {
            let currentTime = Date.now(),
                elapsedTime = currentTime - startTime;
                hundredths = Math.floor(elapsedTime % 1000 / 10)
  
            let Hours = getTimeFormat(hours),
                Minutes = getTimeFormat(minutes),
                Seconds = getTimeFormat(seconds),
                Hundredths = getTimeFormat(hundredths); 
                    
            await clearConsole();
            console.log(`${Hours}:${Minutes}:${Seconds}.${Hundredths}`);
            
            if (elapsedTime >= 1000) {
                startTime = currentTime;
                seconds++;

                if (seconds === 60) {
                    seconds = 0;
                    minutes++;

                    if (minutes === 60) {
                        minutes = 0;
                        hours++;
                    }
                }
            }
        }

        await sleep(1);
    }
}

async function startStopwatch() {
    running = true;
    await clearConsole();
    await Stopwatch();
}
© www.soinside.com 2019 - 2024. All rights reserved.