Javascript timer just for minutes and seconds

mike picture mike · Oct 17, 2013 · Viewed 38.8k times · Source

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?

Answer

Rayon picture Rayon · Oct 17, 2013
  • 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>