倒计时计时器:暂停按钮获胜't暂停或改回播放按钮

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

本文关键字:按钮 暂停 播放 计时器 获胜 倒计时      更新时间:2023-09-26

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

我试图将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中留下剩余的处理程序。因此,当你运行代码笔并单击"开始/暂停"按钮时,你会注意到它正在为计时器添加另一个倒计时。这就是为什么每次点击按钮时倒计时都会加快的原因。

您应该在按钮的一个处理程序中处理单击事件的状态。如果状态已暂停,则处理您的暂停逻辑。如果它正在运行,那么处理您的运行逻辑。但要从一个事件处理程序中完成所有操作。在这种情况下,使用id或class是可以的,但不要随意交换。如果有什么不同的话,使用单击处理程序的Id,然后在dom中交换元素上的类(或应用数据属性)将更好地表达时钟的当前状态/模式。

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