Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a 24hour Countdown timer using Moment.js

Please I need help with implementing a 24 hours countdown timer in moment.js. here is my code :

<script>
window.onload = function(e){

var $clock = $('#clock'),

duration1 = moment.duration({
    'seconds': 30,
    'hour': 0,
    'minutes': 0,
    'days':0
});
duration2 = moment.duration({
    'seconds': 60,
    'hour': 0,
    'minutes': 0,
    'days':0
});

diff=duration2-duration1;
duration=moment.duration(diff, 'milliseconds');


interval = 1000;
setInterval(function(){    
    duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');            
    $('#clock').text(duration.days() + 'd:' + duration.hours()+ 'h:' + duration.minutes()+ 'm:' + duration.seconds() + 's');    
 }, interval);
</script>

The problem is anytime I refresh the page the timer Refreshes also. How do I get around this. And if there is a much better way to implementing this please do share.

Thanks

like image 926
James Blare Avatar asked Sep 05 '26 13:09

James Blare


1 Answers

This is how I would do it:

// create the timestamp here. I use the end of the day here as an example
const end = moment().endOf('day'); 

setInterval(function() {
    const timeLeft = moment(end.diff(moment())); // get difference between now and timestamp
    const formatted = timeLeft.format('HH:mm:ss'); // make pretty

    console.log(formatted); // or do your jQuery stuff here
}, 1000);

This will print a timestamp out every second like this:

09:49:25 
09:49:24 
09:49:23 
09:49:22 
...
like image 173
Aron Avatar answered Sep 08 '26 02:09

Aron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!