为什么我的暂停按钮不工作时,使用javascript设计定时器



我是javascript新手。下面的代码是我设计计时器的实践。它在单击开始按钮时起作用,但不适用于暂停按钮。我花了好几个小时想弄明白,但还是毫无头绪。任何帮助将非常感激!

<!DOCTYPE html>
<html>
<body>
      <div class="inputs" id="inputs-div">
        <input id="hours" type="number" name="hours" max="100" min="0" value="1"/>
        <input id="minutes" type="number" name="minutes" max="59" min="0" value="10"/>
      </div>
      <div class="countdown-div">
         <input id="countdownTimer" type="text" style="display: none" />
      </div>
      <div class="buttons">
        <button id="button-start">Start</button>
        <button id="button-pause">Pause</button>
        <button id="button-cancel" style="display: none">Cancel</button>
        <button id="button-resume" style="display: none">Resume</button>
      </div>
      <script>
         var hours = document.getElementById("hours").value,
             mins = document.getElementById("minutes").value,
             maxtime = parseInt(hours) * 3600 + parseInt(mins) * 60;
         document.getElementById("button-start").addEventListener("click", myFunction);
         function myFunction() {
            document.getElementById("button-start").style.display = "none";
            document.getElementById("button-cancel").style.display = "block";
            document.getElementById("inputs-div").style.display = "none";
            document.getElementById("countdownTimer").style.display = "block";  
         }

         function timedCount() {
           document.getElementById('countdownTimer').value=Math.floor(maxtime/3600)+":"
           +Math.floor(maxtime%3600/60)+":"+maxtime % 3600 % 60;
           maxtime--;
           setTimeout("timedCount()",1000);
         }
         var t=setTimeout("timedCount()",1000);
         function timerPause() {
            clearTimeout(t);
         }
         document.getElementById("button-pause").addEventListener("click", timerPause);
       </script>
</body>
</html>

timedCount()函数中有setTimeout("timedCount()",1000);行。

你需要把它分配给t,这样你仍然可以清除它。此外,我不知道为什么你的函数名称是字符串当你做setTimeout,我不确定这是否有效。通常你只需要输入函数名而不需要()

 function timedCount() {
       document.getElementById('countdownTimer').value=Math.floor(maxtime/3600)+":"
       +Math.floor(maxtime%3600/60)+":"+maxtime % 3600 % 60;
       maxtime--;
       t = setTimeout(timedCount,1000); <--- this line
 }

你应该好好看看setIntervalclearInterval