Rumen Hristov Rumen Hristov - 1 month ago 7
HTML Question

Update timer inside div. JavaScript

I have written a timer. The initial minutes and hours are taken from the user. It should then count down the time. However, I don't know how to convert it to count down in a div. At the moment the action occurs in a prompt box. I don't want this.

function timer() {

var mins = 1;
var secs = 10;

while (mins >= 0) {
for(var i = secs; i > 0; i--) {
setInterval(alert(mins + ":" + i),1000);
}
secs = 59;
mins--;
}
}

Answer

Like I said in your other, similar question: don't make intervals or timeouts in loops.

  1. You're introducing more complexity by adding the while. You don't need it.
  2. Making intervals in loops usually isn't the right idea because you are likely spawning several intervals that will all do the same thing all at the same time.

var el = document.getElementById("timer"),
  mins = 2,
  secs = 0;

function countDown() {
  if (secs || mins) {
    setTimeout(countDown, 100); // Should be 1000, but I'm impatient
  }
  el.innerHTML = mins + ":" + (secs.toString().length < 2 ? "0" + secs : secs); // Pad number
  secs -= 1;
  if (secs < 0) {
    mins -= 1;
    secs = 59;
  }
}

countDown();
<div id="timer"></div>