Update timer inside div. JavaScript

2019-09-13 21:18发布

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

3条回答
贼婆χ
2楼-- · 2019-09-13 21:27

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>

查看更多
疯言疯语
3楼-- · 2019-09-13 21:41

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.

查看更多
ら.Afraid
4楼-- · 2019-09-13 21:45

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>

查看更多
登录 后发表回答