-4

I need to create a javascript timer that will count down to the next 5 minutes. For example let's say the time is 00:07:30, the time will say 02:30 if the time is 15:42:00 the timer will say 03:00 I can't really think of any good way to du this. thank you.

dj_boy
  • 103
  • 1
  • 2
  • 9
  • I did not try any thing, the only thing I can think of is creating a switch with every 5 min in 24 hours, and that is redeculis. – dj_boy Apr 22 '13 at 21:33
  • Take a look at this and follow the link and links, you may be asking a duplicate, http://stackoverflow.com/questions/16134997/how-to-pause-and-resume-a-javascript-timer – Xotic750 Apr 22 '13 at 21:35
  • no, because I need to use the real 5 minutes, not 5 minutes from now, but 5 minutes in the clock, 05, 10, 15, 20, 25, 30.... – dj_boy Apr 22 '13 at 21:38
  • 1
    So just modify one of the many solutions, they handle the live clocking, you just need to start them at the correct time. Don't expect someone to write a solution for you without trying. – Xotic750 Apr 22 '13 at 21:40

3 Answers3

12

There are many ways to do this. My idea is to find out the reminder of current time divide by five minutes (300 seconds).

Demo : http://jsfiddle.net/txwsj/

setInterval(function () {
    var d = new Date(); //get current time
    var seconds = d.getMinutes() * 60 + d.getSeconds(); //convet current mm:ss to seconds for easier caculation, we don't care hours.
    var fiveMin = 60 * 5; //five minutes is 300 seconds!
    var timeleft = fiveMin - seconds % fiveMin; // let's say now is 01:30, then current seconds is 60+30 = 90. And 90%300 = 90, finally 300-90 = 210. That's the time left!
    var result = parseInt(timeleft / 60) + ':' + timeleft % 60; //formart seconds back into mm:ss 
    document.getElementById('test').innerHTML = result;

}, 500) //calling it every 0.5 second to do a count down
Mark Ni
  • 2,276
  • 1
  • 24
  • 33
0

Instead you could try using window.setInterval() like this:

    window.setInterval(function(){
        var time = document.getElementById("secs").innerHTML;
        if (time > 0) {
            time -= 1;
        } else {
            alert ("times up!");
            //or whatever you want
        }
        document.getElementById("secs").innerHTML = time;
    }, 1000);
Raghav Malik
  • 691
  • 1
  • 6
  • 19
-1

If you want to do a timer on your webpage, you can try to use something like this:

<html>  
  <head>
    <script type="text/javascript">
      var now = new Date().getTime();
      var elapsed = new Date().getTime() - now;
      document.getElementById("timer").innerHtml = elapsed;
      if (elapsed > 300000 /*milliseconds in 5 minutes*/) {
        alert ("5 minutes up!");
        //take whatever action you want!
      }
    </script>
  </head>
  <body>
    <div id="timer"></div>
  </body>
</html>
Raghav Malik
  • 691
  • 1
  • 6
  • 19