0

So I am trying to make a timer on Javascript, I'm new so it is very basic. I have it working so that the minutes and the seconds change correctly but when I try to do it in a loop it messes it up. Any help would be great.

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>
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • 9
    why the loop?! whats the purpose of it? – Jonas Wilms Oct 18 '18 at 15:29
  • 3
    Try and figure out yourself what is going on. Break down your program into chunks, if it helps write down what happens at each stage of the operation. Perhaps you could simplify the problem first, try writing a program that counts down one number, then once that works, expand it to 2 numbers. Good luck! – Christopher Moore Oct 18 '18 at 15:40
  • The point of the loop is that when the seconds value reaches 0 it makes the minutes drop by one. The context is for a timer in a game, certain things will make the seconds drop so I need the minutes to remain linked to the seconds. – T_McMillan97 Oct 18 '18 at 15:47
  • Possible duplicate of [How to create an accurate timer in javascript?](https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript) – Liam Oct 18 '18 at 15:56
  • @T_McMillan97 you do not need the loop here. You could just directly check the condition (seconds <= 0) and then execute the main part of your method. – dthulke Oct 18 '18 at 16:42

1 Answers1

0

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

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

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

startCountdown(5, 3)
<p id="timer"></p>
AndreasPizsa
  • 1,736
  • 19
  • 26