搜尋

首頁  >  問答  >  主體

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粉014293738441 天前616

全部回覆(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
  • 取消回覆