创建倒计时计时器时出现问题-分钟/秒

时间:2019-06-02 20:42:33

标签: javascript jquery

我正在以分钟和秒为单位创建一个倒计时计时器,该倒计时计时器显示在页面上-似乎所有代码都可以正常工作。唯一的问题是,当警报框弹出时,我希望时钟也停止倒计时。

我认为在弹出的警报下包含return关键字可以解决此问题,但时钟会一直滴答作响。

下面是代码。任何帮助都会很棒。

  window.onload = function() {

  var hour = 1;
  var sec = 59;

  setInterval(function() {
    document.getElementById("timer").innerHTML = hour + " : " + sec;
    sec--;
     if (sec == 0) {
       hour--;
       sec = 59; 
       } 
       if (hour == 1 && sec == 51)
        {
            alert("Stop, you have not completed the task in the alotted time");
            return;
        }             
    }, 1000);

}

2 个答案:

答案 0 :(得分:0)

您需要设置超时,而不是间隔。间隔触发,直到它们停止。超时发生一次。

const interval = setInterval( function() {
  document.getElementById("timer").innerHTML = hour + " : " + sec;
  sec--;
  if (sec == 0) {
    hour--;
    sec = 59; 
   }
});

const timeoutPeriod = 2 * 60 * 60 * 1000;

setTimeout(
  function(){
    clearInterval(interval);
    alert("Stop, you have not completed the task in the alotted time");
  }, timeoutPeriod
);

答案 1 :(得分:0)

为此,您需要将该时间间隔保存在变量中,然后使用clearInterval停用该时间间隔。因此您的代码将如下所示:

 window.onload = function() {

  var hour = 1;
  var sec = 59;

  let counting_interval = setInterval(function() {
    document.getElementById("timer").innerHTML = hour + " : " + sec;
    sec--;
     if (sec == 0) {
       hour--;
       sec = 59; 
       } 
       if (hour == 1 && sec == 51)
        {
            alert("Stop, you have not completed the task in the alotted time");
            clearInterval(counting_interval); // pass the interval as the argument and it will stop to call the interval anymore
            return;
        }             
    }, 1000);

}