Skip to content Skip to sidebar Skip to footer

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. A

Solution 1:

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>

Solution 2:

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>

Solution 3:

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.


Post a Comment for "Update Timer Inside Div. JavaScript"