[javascript] plain count up timer in 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.

This question is related to javascript

The answer is


Here is an React (Native) version:

import React, { Component } from 'react';
import {
    View,
    Text,
} from 'react-native';

export default class CountUp extends Component  {

    state = {
        seconds: null,
    }

    get formatedTime() {
        const { seconds } = this.state;

        return [
            pad(parseInt(seconds / 60)),
            pad(seconds % 60),
        ].join(':');
    }

    componentWillMount() {
        this.setState({ seconds: 0 });
    }

    componentDidMount() {
        this.timer = setInterval(
            () => this.setState({
                seconds: ++this.state.seconds
            }),
            1000
        );
    }

    componentWillUnmount() {
        clearInterval(this.timer);
    }

    render() {
        return (
            <View>
                <Text>{this.formatedTime}</Text>
            </View>
        );
    }
}

function pad(num) {
    return num.toString().length > 1 ? num : `0${num}`;
}

Timer for jQuery - smaller, working, tested.

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

Pure JavaScript:

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

Update:

This answer shows how to pad.

Stopping setInterval MDN is achieved with clearInterval MDN

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

Fiddle


Note: Always include jQuery before writing jQuery scripts

Step1: setInterval function is called every 1000ms (1s)

Stpe2: In that function. Increment the seconds

Step3: Check the Conditions

_x000D_
_x000D_
<span id="count-up">0:00</span>_x000D_
<script>_x000D_
   var min    = 0;_x000D_
      var second = 00;_x000D_
      var zeroPlaceholder = 0;_x000D_
      var counterId = setInterval(function(){_x000D_
                        countUp();_x000D_
                      }, 1000);_x000D_
_x000D_
      function countUp () {_x000D_
          second++;_x000D_
          if(second == 59){_x000D_
            second = 00;_x000D_
            min = min + 1;_x000D_
          }_x000D_
          if(second == 10){_x000D_
              zeroPlaceholder = '';_x000D_
          }else_x000D_
          if(second == 00){_x000D_
              zeroPlaceholder = 0;_x000D_
          }_x000D_
_x000D_
          document.getElementById("count-up").innerText = min+':'+zeroPlaceholder+second;_x000D_
      }_x000D_
</script>
_x000D_
_x000D_
_x000D_


The following code works as a count-up timer. It's pure JavaScript code which shows hour:minute:second. It also has a STOP button:

_x000D_
_x000D_
var timerVar = setInterval(countTimer, 1000);
var totalSeconds = 0;
function countTimer() {
           ++totalSeconds;
           var hour = Math.floor(totalSeconds /3600);
           var minute = Math.floor((totalSeconds - hour*3600)/60);
           var seconds = totalSeconds - (hour*3600 + minute*60);
           if(hour < 10)
             hour = "0"+hour;
           if(minute < 10)
             minute = "0"+minute;
           if(seconds < 10)
             seconds = "0"+seconds;
           document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
        }

    
_x000D_
<div id="timer"></div>
<div id ="stop_timer" onclick="clearInterval(timerVar)">Stop time</div>
        
        
_x000D_
_x000D_
_x000D_


Fiddled around with the Bakudan's code and other code in stackoverflow to get everything in one.

Update #1 : Added more options. Now Start, pause, resume, reset and restart. Mix the functions to get desired results.

Update #2 : Edited out previously used JQuery codes for pure JS and added as code snippet.

For previous Jquery based fiddle version : https://jsfiddle.net/wizajay/rro5pna3/305/

_x000D_
_x000D_
var Clock = {_x000D_
  totalSeconds: 0,_x000D_
  start: function () {_x000D_
    if (!this.interval) {_x000D_
        var self = this;_x000D_
        function pad(val) { return val > 9 ? val : "0" + val; }_x000D_
        this.interval = setInterval(function () {_x000D_
          self.totalSeconds += 1;_x000D_
_x000D_
          document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));_x000D_
          document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));_x000D_
        }, 1000);_x000D_
    }_x000D_
  },_x000D_
_x000D_
  reset: function () {_x000D_
    Clock.totalSeconds = null; _x000D_
    clearInterval(this.interval);_x000D_
    document.getElementById("min").innerHTML = "00";_x000D_
    document.getElementById("sec").innerHTML = "00";_x000D_
    delete this.interval;_x000D_
  },_x000D_
  pause: function () {_x000D_
    clearInterval(this.interval);_x000D_
    delete this.interval;_x000D_
  },_x000D_
_x000D_
  resume: function () {_x000D_
    this.start();_x000D_
  },_x000D_
_x000D_
  restart: function () {_x000D_
     this.reset();_x000D_
     Clock.start();_x000D_
  }_x000D_
};_x000D_
_x000D_
_x000D_
document.getElementById("startButton").addEventListener("click", function () { Clock.start(); });_x000D_
document.getElementById("pauseButton").addEventListener("click", function () { Clock.pause(); });_x000D_
document.getElementById("resumeButton").addEventListener("click", function () { Clock.resume(); });_x000D_
document.getElementById("resetButton").addEventListener("click", function () { Clock.reset(); });_x000D_
document.getElementById("restartButton").addEventListener("click", function () { Clock.restart(); });
_x000D_
<span id="min">00</span>:<span id="sec">00</span>_x000D_
_x000D_
<input id="startButton" type="button" value="Start">_x000D_
<input id="pauseButton" type="button" value="Pause">_x000D_
<input id="resumeButton" type="button" value="Resume">_x000D_
<input id="resetButton" type="button" value="Reset">_x000D_
<input id="restartButton" type="button" value="Restart">
_x000D_
_x000D_
_x000D_


Here is one using .padStart():

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8' />
  <title>timer</title>
</head>
<body>
  <span id="minutes">00</span>:<span id="seconds">00</span>

  <script>
    const minutes = document.querySelector("#minutes")
    const seconds = document.querySelector("#seconds")
    let count = 0;

    const renderTimer = () => {
      count += 1;
      minutes.innerHTML = Math.floor(count / 60).toString().padStart(2, "0");
      seconds.innerHTML = (count % 60).toString().padStart(2, "0");
    }

    const timer = setInterval(renderTimer, 1000)
  </script>
</body>
</html>

From MDN:

The padStart() method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.


I had to create a timer for teachers grading students' work. Here's one I used which is entirely based on elapsed time since the grading begun by storing the system time at the point that the page is loaded, and then comparing it every half second to the system time at that point:

var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds
localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page

function startTimeCounter() {
    var now = Math.floor(Date.now() / 1000); // get the time now
    var diff = now - startTime; // diff in seconds between now and start
    var m = Math.floor(diff / 60); // get minutes value (quotient of diff)
    var s = Math.floor(diff % 60); // get seconds value (remainder of diff)
    m = checkTime(m); // add a leading zero if it's single digit
    s = checkTime(s); // add a leading zero if it's single digit
    document.getElementById("idName").innerHTML = m + ":" + s; // update the element where the timer will appear
    var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer
}

function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}

startTimeCounter();

This way, it really doesn't matter if the 'setTimeout' is subject to execution delays, the elapsed time is always relative the system time when it first began, and the system time at the time of update.


Check out these solutions:

Compute elapsed time


Extending from @Chandu, with some UI added:

<html>
<head>
<script   src="https://code.jquery.com/jquery-3.2.1.min.js"   integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="   crossorigin="anonymous"></script>
</head>
<style>
button {
background: steelblue; 
border-radius: 4px; 
height: 40px; 
width: 100px; 
color: white; 
font-size: 20px; 
cursor: pointer; 
border: none; 
}
button:focus {
outline: 0; 
}
#minutes, #seconds {
font-size: 40px; 
}
.bigger {
font-size: 40px; 
}
.button {
  box-shadow: 0 9px #999;
}

.button:hover {background-color: hotpink}

.button:active {
  background-color: hotpink;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}
</style>
<body align='center'>
<button onclick='set_timer()' class='button'>START</button>
<button onclick='stop_timer()' class='button'>STOP</button><br><br>
<label id="minutes">00</label><span class='bigger'>:</span><label id="seconds">00</label>
</body>
</html>
<script>

function pad(val) {
  valString = val + "";
  if(valString.length < 2) {
     return "0" + valString;
     } else {
     return valString;
     }
}

totalSeconds = 0;
function setTime(minutesLabel, secondsLabel) {
    totalSeconds++;
    secondsLabel.innerHTML = pad(totalSeconds%60);
    minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
    }

function set_timer() {
    minutesLabel = document.getElementById("minutes");
    secondsLabel = document.getElementById("seconds");
    my_int = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
}

function stop_timer() {
  clearInterval(my_int);
}


</script>

Looks as follows:

enter image description here


Just wanted to put my 2 cents in. I modified @Ajay Singh's function to handle countdown and count up Here is a snip from the jsfiddle.

var countDown = Math.floor(Date.now() / 1000)
runClock(null, function(e, r){ console.log( e.seconds );}, countDown);
var t = setInterval(function(){
  runClock(function(){
    console.log('done');
    clearInterval(t);
  },function(timeElapsed, timeRemaining){
    console.log( timeElapsed.seconds );
  }, countDown);
}, 100);

https://jsfiddle.net/3g5xvaxe/


@Cybernate, I was looking for the same script today thanks for your input. However I changed it just a bit for jQuery...

function clock(){
    $('body').prepend('<div id="clock"><label id="minutes">00</label>:<label id="seconds">00</label></div>');
         var totalSeconds = 0;
        setInterval(setTime, 1000);
        function setTime()
        {
            ++totalSeconds;
            $('#clock > #seconds').html(pad(totalSeconds%60));
            $('#clock > #minutes').html(pad(parseInt(totalSeconds/60)));
        }
        function pad(val)
        {
            var valString = val + "";
            if(valString.length < 2)
            {
                return "0" + valString;
            }
            else
            {
                return valString;
            }
        }
}
$(document).ready(function(){
    clock();
    });

the css part:

<style>
#clock {
    padding: 10px;
    position:absolute;
    top: 0px;
    right: 0px;
    color: black;
}
</style>