Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counter Countup implemented with moment js

I am trying to implement a counter starts at 00:00:00 (hh:mm:ss) and shows it every second in a span. I am not getting to start with hour = 00. It shows me 10:00:00 at the beginning.

The code is following:

var startTimestamp;
function startTimer()
{
    var startTimestamp = moment().startOf("day");
    setInterval(function() {
        startTimestamp++;
        document.getElementById('timer').innerHTML = 
            moment.unix(startTimestamp).format('hh:mm:ss');
    }, 1000);
}

Any idea why it doesn't work?

like image 792
MrScf Avatar asked Dec 19 '22 01:12

MrScf


1 Answers

Since startTimestamp is a moment object you can modify its value using add() instead of using startTimestamp++. Note that add():

Mutates the original moment by adding time.

Then there is no reason to use moment.unix(), you can simply use format() on startTimestamp.

Finally, as format() docs states, lowercase hh stands for 01 02 ... 11 12 hours while uppercase HH stands for 00 01 ... 22 23, so I think you have to use the latter.

Here a live sample:

function startTimer()
{
    var startTimestamp = moment().startOf("day");
    setInterval(function() {
        startTimestamp.add(1, 'second');
        document.getElementById('timer').innerHTML = 
            startTimestamp.format('HH:mm:ss');
    }, 1000);
}

startTimer();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

<div id="timer"></div>
like image 164
VincenzoC Avatar answered Dec 29 '22 22:12

VincenzoC