Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time remaining to the next 5 minutes - Javascript

Tags:

javascript

I am trying to display the time remaining for the next 5 minutes (snapped to the full 5 minutes of the current time e.g., 15:05, 15:10..)

I was able to achieve the same for the time remaining for next Hour (Not minutes):

<span class="timer"></span>
<script>
function secondPassed() {
    var cur_date = new Date();
    var hour = cur_date.getHours();
    var minutes = cur_date.getMinutes();
    var seconds = cur_date.getSeconds();
    var minutes_remain = parseInt(59 - parseInt(minutes));
    var seconds_remain = parseInt(60 - parseInt(seconds));

    var timers = document.getElementsByClassName('timer');
    for (var i = 0; i < timers.length; i++) {
        timers[i].innerHTML = minutes_remain+":"+seconds_remain;
    }

}

var countdownTimer = setInterval(secondPassed, 1000);
</script>

JSfiddle : http://jsfiddle.net/ov0oo5f7/

like image 867
mediaroot Avatar asked Sep 24 '14 11:09

mediaroot


2 Answers

Something like this?

function secondPassed() {
    var cur_date = new Date();
    var minutes = cur_date.getMinutes();
    var seconds = cur_date.getSeconds();
    
    var timers = document.getElementsByClassName('timer');
    for (var i = 0; i < timers.length; i++) {
        timers[i].innerHTML = (4 - minutes % 5) + ":" + (seconds >= 50 ? "0" : "") + (59 - seconds);
    }
    
}

var countdownTimer = setInterval(secondPassed, 1000);
<span class="timer"></span>
like image 158
Mandera Avatar answered Nov 08 '22 00:11

Mandera


You can reduce the code a bit and to make it more accurate, use setTimeout and call the function as close as reasonable to the next full second. setInterval will slowly drift.

// Return the time to next 5 minutes as m:ss
function toNext5Min() {

  // Get the current time
  var secs = (new Date() / 1000 | 0) % 300;

  // Function to add leading zero to single digit numbers
  function z(n){return (n < 10? '0' : '') + n;}

  // Return m:ss
  return (5 - secs/60 | 0) + ':' + z(60 - (secs%60 || 60));
}

// Call the function just after the next full second
function runTimer() {
  console.log(toNext5Min());
  var now = new Date();
  setTimeout(runTimer, 1020 - now % 1000);
}

The above ticks over on the full minute so that at say 10:00:00 it shows 5:00. If you'd rather is showed 0:00, then the last line of toNext5Min should be:

  return (5 - (secs? secs/60 : 5) | 0) + ':' + z(60 - (secs%60 || 60));
like image 36
RobG Avatar answered Nov 08 '22 00:11

RobG