Reputation: 33
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
Upvotes: 3
Views: 7331
Reputation: 7652
I think estimating time left logic might have a bug. The statement is const timeLeft = moment(end.diff(moment(), true))
.
What I found was ...
const end = moment().endOf('day'); // Mon Oct 22 2018 23:59:59 GMT+0900
const now = moment(); // Mon Oct 22 2018 14:38:30 GMT+0900
const timeLeft = moment(end.diff(moment(), true)); // diff = 33689322
const formatted = timeLeft.format('HH:mm:ss'); // 18:21:29
When you calculate with Date
object, it will return 9 hours something. - I think that initializing moment object with diff returns causes this bug.
And this is the final form of my solution.
const end = moment().endOf('day');
console.log('End date', moment(), end, end.diff(moment()), moment().diff(end));
const timeLeft = moment.duration(end.diff(moment())); // Use duration
const formatted =
this.checkDigit(timeLeft.hours()) + ':'
+ this.checkDigit(timeLeft.minutes()) + ':'
+ this.checkDigit(timeLeft.seconds()); // checkDigit is a function which adds 0 to the numbers under 10
The major difference is duration
function. Of course, it could be a version difference.
Upvotes: 2
Reputation: 3038
You could use localStorage to save the original timestamp. Another option is to save it on the server (database?). Either way, if you refresh the page, you will still count down to the same time.
Upvotes: 0
Reputation: 9246
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
...
Upvotes: 5