Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plain count up timer in javascript

Tags:

javascript

I am looking for a simple count up timer in javascript. All the scripts I find are 'all singing all dancing'. I just want a jQuery free, minimal fuss count up timer that displays in minutes and seconds. Thanks.

like image 654
Mark Avatar asked Apr 01 '11 18:04

Mark


People also ask

How do you make a 10 second timer in JavaScript?

To create a simple 10 second countdown with JavaScript, we use the setInterval method. to add a progress element. let timeleft = 10; const downloadTimer = setInterval(() => { if (timeleft <= 0) { clearInterval(downloadTimer); } document.


2 Answers

Check this:

var minutesLabel = document.getElementById("minutes");  var secondsLabel = document.getElementById("seconds");  var totalSeconds = 0;  setInterval(setTime, 1000);    function setTime() {    ++totalSeconds;    secondsLabel.innerHTML = pad(totalSeconds % 60);    minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));  }    function pad(val) {    var valString = val + "";    if (valString.length < 2) {      return "0" + valString;    } else {      return valString;    }  }
<label id="minutes">00</label>:<label id="seconds">00</label>
like image 182
Chandu Avatar answered Sep 22 '22 09:09

Chandu


Timer for jQuery - smaller, working, tested.

    var sec = 0;      function pad ( val ) { return val > 9 ? val : "0" + val; }      setInterval( function(){          $("#seconds").html(pad(++sec%60));          $("#minutes").html(pad(parseInt(sec/60,10)));      }, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <span id="minutes"></span>:<span id="seconds"></span>

Pure JavaScript:

    var sec = 0;      function pad ( val ) { return val > 9 ? val : "0" + val; }      setInterval( function(){          document.getElementById("seconds").innerHTML=pad(++sec%60);          document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));      }, 1000);
<span id="minutes"></span>:<span id="seconds"></span>

Update:

This answer shows how to pad.

Stopping setInterval MDN is achieved with clearInterval MDN

var timer = setInterval ( function(){...}, 1000 ); ... clearInterval ( timer ); 

Fiddle

like image 29
Bakudan Avatar answered Sep 20 '22 09:09

Bakudan