首页  >  问答  >  正文

JS 中的 SpeedCubing 秒表

在代码块中内置了一个计时器。现在计时器通过按钮启动/停止,但我需要它在释放空格按钮时运行,并且我需要它在按下空格按钮时停止。我已经尝试解决这个问题大约两天了,但似乎找不到解决方案。每次我尝试停止计时器时,当我释放空格按钮时,计时器都会再次启动。

let startDate;
let timeoutID = 0;
let time;
let started = false;
let timerRunOut = false;

function start(){
    if(!started){
        startDate = new Date();
        startTimer();
        started = true;
    }
}
function stop(){
    if(started){
        clearTimeout(timeoutID);
        started = false;
    }
}

function startTimer () {
    let current = new Date();
    time = (current - startDate);

    let timeMS = time;

    let ms = timeMS % 1000;
    timeMS = (timeMS - ms) / 1000;
    let seconds = timeMS % 60;
    timeMS = (timeMS - seconds) / 60;
    let mins = timeMS % 60;

    if(seconds < 10){
        document.getElementById("seconds").innerText = "0" + seconds;
    }else{
        document.getElementById("seconds").innerText = seconds;
    }

    if(mins > 0 && mins < 10){
        document.getElementById("minutes").innerText = "0" + mins + ":";
    }else if(mins > 0){
        document.getElementById("minutes").innerText = mins + ":";
    }else{
        document.getElementById("minutes").innerText = "";
    }

    if(ms < 10){
        document.getElementById("tens").innerText = "00" + ms;
    }
    else if(ms < 100){
        document.getElementById("tens").innerText = "0" + ms;
    }else{
        document.getElementById("tens").innerText = ms;
    }

    timeoutID = setTimeout(startTimer, 0);
}

我尝试添加事件侦听器并添加条件,但没有任何效果,当计时器停止时,当我释放空格按钮时,它总是会再次启动。

P粉014293738P粉014293738425 天前602

全部回复(1)我来回复

  • P粉762730205

    P粉7627302052023-09-15 00:51:03

    我找到了解决方案,我需要给 Andre 一点功劳,他帮助我解决了问题这个出来了。

    let spaceUp = 0;
    function startHandler(event){
        if(event.code === "Space" && spaceUp < 1){
           start();
           spaceUp ++;
           document.addEventListener("keydown", stopHandler);
           document.removeEventListener("keyup", startHandler);
        
        }else if(spaceUp == 1){
            spaceUp = 0;
        }
        document.getElementById("timer").style.color = "black";
    }
    function stopHandler(event){
        if(event.code === "Space"){
            stop();
            document.removeEventListener("keydown", stopHandler);
            document.getElementById("timer").style.color = "red";
            document.addEventListener("keyup", startHandler);
        }
    }
    
    document.addEventListener("keyup", startHandler);
    
    document.addEventListener("keydown", function(e){
        if(e.code === "Space" && !started){
            document.getElementById("timer").style.color = "green";
         }
    })

    回复
    0
  • 取消回复