Rumen Hristov Rumen Hristov - 1 month ago 12
Javascript Question

I don't know how to make this show within the html. what is wrong with this script?

I wrote the following js. I want it to count down inside the div-element. Please help. I've exhausted everything I could think of. Is this a problem in the HTML or am I just not passing things correctly in my js code?



<html>

<head>
<title>Counter</title>
<script>
var el, usr_t, split_list, mins, secs;

function getValues() {

el = document.getElementById("timer");

usr_t = document.getElementById("time").value;
split_list = usr_t.split(":").map(Number);

mins = split_list[0];
secs = split_list[1];

while (mins >= 0) {
for (var i = secs; i > 0; i--) {
setDelay(i);
}
secs = 59;
mins--;
}
}

function setDelay(i) {
setTimeout(function() {
el.innerHTML = (mins + ":" + secs);
}, 1000);
}
</script>
</head>

<body>
<form>
Enter your time: (mm:ss)
<br>
<input type="text" id="time">
<br>
<input type="submit" value="Start" onclick="getValues()">
</form>

<div id="timer"></div>
</body>

</html>




Answer

The following is more or less the same code I showed you in your other question Update timer inside div. JavaScript which built my answer to your other question How to repeatedly update the contents of a <div> by only using JavaScript?.

You are still using setTimeout() in a loop. That while loop is calling setDelay() over and over again which creates a bunch of timeouts that will all call their given callback at the same time which is to set your output div to the time left (which will be 0 since the decrementer loop is finished).

var el = document.getElementById("timer"),
  minsInput = document.getElementById("mins"),
  secsInput = document.getElementById("secs"),
  timerForm = document.getElementById("timer-form");


function countAway() {
  var mins = minsInput.value,
    secs = secsInput.value;

  (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;
    }
  }());
}

timerForm.addEventListener("submit", function(submitEvent) {
  countAway();
  submitEvent.preventDefault();
});
<form id="timer-form" action="#" method="post">
  <fieldset>
    <legend>Timer</legend>
    <ul>
      <li>
        <label for="mins">Minutes</label>
        <input id="mins" type="number" value="1" min="0" max="60">
      </li>
      <li>
        <label for="secs">Seconds</label>
        <input id="secs" type="number" value="30" min="0" max="60">
      </li>
      <li>
        <button type="submit">Start</button>
    </ul>
  </fieldset>
</form>

<div id="timer"></div>