JavaScript count down, add hours & minutes

前端 未结 3 2003
无人共我
无人共我 2021-02-11 04:03

So, I have the below (seconds countdown) in good order. But! I am trying to add hours & minutes as apart of the count down as well. Ideally keeping the same structure, and j

3条回答
  •  难免孤独
    2021-02-11 04:31

    var totalSeconds = 3723; // lets say we have 3723 seconds on the countdown
                             // that's 1 hour, 2 minutes and 3 seconds.
    
    var hours   = Math.floor(totalSeconds / 3600 );
    var minutes = Math.floor(totalSeconds % 3600 / 60);
    var seconds = totalSeconds % 60;
    
    var result = [hours, minutes, seconds].join(':');
    console.log(result);
    // 1:2:3
    
    • hours is seconds divided by the number of seconds in hour (3600) rounded down
    • minutes is the remainder of the above division, divided by the number of seconds in a minute (60), rounded down.
    • seconds is the remainder of total seconds divided by seconds in a minute.

    Each calculation after hour has to use a modulus calculation to get the remainder, because you don't care about total time at that step, just progress to the next tick.

提交回复
热议问题