Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript timer just for minutes and seconds

I found a JSFiddle with a timer that counts up every second. Except i want this to work with just the minutes and seconds. No hours.

Any ideas?

like image 839
mike Avatar asked Oct 17 '13 14:10

mike


4 Answers

  • DATE_OBJ.getSeconds() to get seconds of Date object.
  • DATE_OBJ. getMinutes() to get minutes of Date object.
  • setInterval to invoke handler function after every second(1000ms).

var handler = function() {
  var date = new Date();
  var sec = date.getSeconds();
  var min = date.getMinutes();
  document.getElementById("time").textContent = (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec);
};
setInterval(handler, 1000);
handler();
<h1 id="time" style="text-align: center"></h1>
like image 112
Rayon Avatar answered Oct 17 '22 02:10

Rayon


Here's a very hackish approach - http://jsfiddle.net/gPrwW/1/

HTML -

<div id="worked">31:14</div>

JS :

$(document).ready(function (e) {
    var $worked = $("#worked");

    function update() {
        var myTime = $worked.html();
        var ss = myTime.split(":");
        var dt = new Date();
        dt.setHours(0);
        dt.setMinutes(ss[0]);
        dt.setSeconds(ss[1]);

        var dt2 = new Date(dt.valueOf() + 1000);
        var temp = dt2.toTimeString().split(" ");
        var ts = temp[0].split(":");

        $worked.html(ts[1]+":"+ts[2]);
        setTimeout(update, 1000);
    }

    setTimeout(update, 1000);
});
like image 37
Vandesh Avatar answered Oct 17 '22 03:10

Vandesh


The precise way of handling this is the following:

  1. store the time of the start of the script
  2. in a function that gets called repeatedly get the time elapsed
  3. convert the elapsed time in whatever format you want and show it

Sample code:

var initialTime = Date.now();

function checkTime(){
  var timeDifference = Date.now() - initialTime;
  var formatted = convertTime(timeDifference);
  document.getElementById('time').innerHTML = '' + formatted;
}

function convertTime(miliseconds) {
  var totalSeconds = Math.floor(miliseconds/1000);
  var minutes = Math.floor(totalSeconds/60);
  var seconds = totalSeconds - minutes * 60;
  return minutes + ':' + seconds;
}
window.setInterval(checkTime, 100);

You can easily change the granularity of checking the time (currently set at 0.1 seconds). This timer has the advantage that it will never be out of sync when it updates.

like image 5
Tibos Avatar answered Oct 17 '22 01:10

Tibos


You can make a function that increments a counter every time it's called, shows the value as: counter/60 minutes, counter%60 seconds

Then you can use the setInterval function to make JavaScript call your code every second. It's not extremely precise, but it's good enough for simple timers.

like image 3
Emre Avatar answered Oct 17 '22 02:10

Emre