倒数计时器:暂停按钮不会暂停或变回播放按钮

CountDown Timer: pause button won't pause or change back into play button

我在尝试暂停倒数计时器时遇到问题。我试图做到这一点,所以在我点击播放按钮后,按钮变成了暂停按钮。但由于某种原因它不会暂停。

我尝试将 id"pButton" 更改为 "pauseButton",这是有效的,但我的暂停 onclick 功能似乎不会变回 pButton,有什么帮助吗?(clearinterval(timecounter ), timercounter 是一个全局变量,因此它可以访问它。)如果您需要查看,这里还有代码笔上的完整代码:http://codepen.io/freefora11/pen/eJdVjZ

//when play button is pressed
    if(document.getElementById("pButton")){
        document.getElementById("pButton").onclick=function(){

            //change the id of the button
            if(document.getElementById("pButton")){
                document.getElementById("pButton").id = "pauseButton";
            }

            //variables
            strMin = document.getElementById("test").innerHTML;
            var res = strMin.split(":",2);
            min = parseInt(res[0]);
            min= min * 60;
            var sec = parseInt(res[1]);
            timeInSeconds = min + sec;



            //set interval to start keeping track each second that has passed
            timeCounter = setInterval(function() {
              timeInSeconds--;

              // If we hit 0 seconds clear the timer
              if (timeInSeconds <= 0) {
                clearInterval(timeCounter);
              }

              // Display the current time
              displayTime();
            }, 1000);
        }
    }

    //when the pause button is clicked
    if(document.getElementById("pauseButton")){
        document.getElementById("pauseButton").onclick=function(){

            //stop the interval
            clearInterval(timeCounter);

            //change the id of the play button from pauseButton to pButton again
            if(document.getElementById("pauseButton")){
                document.getElementById("pauseButton").id ="pButton";
            }

        }
    }

更改 Id 仍会在 DOM 中留下处理程序的残余。因此,当您 运行 您的 codepen 并单击 Start/Pause 按钮时,您会注意到它正在向计时器添加另一个倒计时。这就是为什么每次单击按钮时倒计时都会加快的原因。

您应该在按钮的一个处理程序中处理单击事件的状态。如果状态暂停,则处理您的暂停逻辑。如果它是 运行ning,那么处理你的 运行ning 逻辑。但是从一个事件处理程序完成这一切。在这种情况下,使用 id 或 class 没问题,但不要即时将其换掉。如果有的话,使用 Id 作为点击处理程序,然后在 dom 中的元素上交换 class (或应用数据属性)会更好地表达时钟的当前 state/mode .

尽管如此,请处理您 javascript 中的逻辑。如果您选择这样做,请使用 dom 状态来应用样式(例如在 CSS 中选择)。