放入循环时,JavaScript计时器中断

时间:2018-10-18 15:27:36

标签: javascript

因此,我试图在Javascript上使用计时器,我是新手,所以它非常基础。我让它工作,以便分钟和秒正确更改,但是当我尝试以循环方式进行操作时,会弄乱它。任何帮助都会很棒。

var seconds = 5;
var minutes = 3;

function countdown() {
  for (i = 0; i < 3; i++) {
    if (seconds > 0) {
      seconds--;
      setTimeout("countdown()", 1000);
    } else if (seconds <= 0) {
      minutes--;
      seconds = 5;
    }
  }

  document.getElementById("timer").innerHTML = minutes + "M " + seconds + "S";
}

countdown();
<p id="timer"></p>

1 个答案:

答案 0 :(得分:0)

function startCountdown(minutes, seconds) {
  updateElement()
  var timerId = setInterval(function() {

   if(--seconds == 0) {
      seconds = 59
      --minutes
    }
 
    if(minutes === 0) clearInterval(timerId)
    updateElement()
  }, 1000);

  function updateElement() {
    document.getElementById("timer").innerHTML = minutes + "M " + seconds + "S"
  }
}

startCountdown(5, 3)
<p id="timer"></p>