Rumen Hristov Rumen Hristov - 1 year ago 55
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?


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--) {
secs = 59;

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

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

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


Answer Source

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) {
<form id="timer-form" action="#" method="post">
        <label for="mins">Minutes</label>
        <input id="mins" type="number" value="1" min="0" max="60">
        <label for="secs">Seconds</label>
        <input id="secs" type="number" value="30" min="0" max="60">
        <button type="submit">Start</button>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download