0

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--;
    }
}
Rumen Hristov
  • 867
  • 2
  • 13
  • 29
  • 1
    Your code with setInterval works ...just call timer() – Geeky Oct 18 '16 at 23:04
  • Or else let us know what you are looking for – Geeky Oct 18 '16 at 23:04
  • @Geeky - you have to actually prove it, post a fiddle of the code working etc. – adeneo Oct 18 '16 at 23:07
  • the first code works, ya. I said that myself. But I need it to show the countdown automatically inside the html. Not in a prompt box. – Rumen Hristov Oct 18 '16 at 23:10
  • What do you mean "*no luck*"? What is or isn't working? This question is *really* similar to your other question: [How to repeatedly update the contents of a
    by only using JavaScript?](http://stackoverflow.com/q/40118795/691711).
    – zero298 Oct 18 '16 at 23:11
  • Yes, it is. I tried to figgle the concept from my other qn into the big picture (here). – Rumen Hristov Oct 18 '16 at 23:12
  • @zero298 I just can't get this to work without introducing setInterval or setTimeout inside a loop. So here is the actual code I needed to modify. Maybe now I can make it work. – Rumen Hristov Oct 18 '16 at 23:14
  • How many `setInterval()s` are there? Did you mean `setTimeout()` instead..? – Redu Oct 18 '16 at 23:20

3 Answers3

2

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>
Community
  • 1
  • 1
zero298
  • 25,467
  • 10
  • 75
  • 100
  • yes. This is exactly what I need. However, is there a simpler way to this without using recursion and preferebly simpler logic? – Rumen Hristov Oct 18 '16 at 23:40
  • This works here, but doesn't work in my html document. I put the script in the head section. If I declare all variables outside the function, they are not visible inside. If I put it inside, the div just blinks 2:10 in an instant and that's it. – Rumen Hristov Oct 19 '16 at 01:01
  • 1
    1. Recursion is the right way to use a repeated setTimeout, only it isn't really recursion because the function is not calling itself, it's just _scheduling_ a _later_ call to it. The function does its business then calls setTimeout so it will be called again later. 2. If you put the script in the head section it is going to start executing before the DOM is built — the `div id="timer"` won't exist yet. You need to either put the script at the end (near the `

    ` tag) or wait for the DOMContentLoaded event before starting execution.

    – Stephen P Oct 19 '16 at 19:54
1

Please check this by "Run code snippet" and confirm this is what you are trying,

var seconds = 60;

function timer() {

    document.getElementById('time').innerHTML = 'Seconds : ' + (seconds--).toString();

   if(seconds >= 0) {
      setTimeout(timer, 1000);
   }
}

timer();
<div id="time"></div>
Aruna
  • 448
  • 3
  • 12
0

I would do this as follows;

var insertZero = n => n < 10 ? "0"+n : ""+n,
     printTime = n => time.textContent = insertZero(~~(n/3600)%3600)+":"+insertZero(~~(n/60)%60)+":"+insertZero(n%60),
 countDownFrom = n => (printTime(n), setTimeout(_ => n ? sid = countDownFrom(--n)
                                                       : console.log("ignition:",n), 1000)),
           sid;
countDownFrom(3610);
setTimeout(_ => clearTimeout(sid),20005);
<div id="time"></div>

It stops in 20 seconds for the sake of the demo purposes.

Redu
  • 25,060
  • 6
  • 56
  • 76