'Momentjs Countdown timer on Vuejs
I'm trying to create a vuejs page with a counter timer of 5 minutes. (ie 5:00 ... 4:59.. so on..) I never used momentjs before, I read moment docs but can't understand the implementation for it. I appreciate someone helps me to implement it. I'm a learner.
<template>
<div>{{ time }}</div>
</template>
<script>
var moment = require("moment");
export default {
data() {
return {
time: "",
};
},
mounted() {},
methods: {},
};
</script>
Solution 1:[1]
There is a hosted solution here: https://codesandbox.io/s/so-countdown-vuejs-momentjs-96hdw?file=/src/App.vue
Here is how to do a countdown in Vuejs with momentjs
<template>
<div>{{ formatedCountdown || 'countdown over' }}</div>
</template>
<script>
import * as moment from 'moment'
import 'moment-duration-format'
export default {
data() {
return {
countdown: 300, // 5min
}
},
mounted() {
const stopCountdown = setInterval(() => {
console.log('current countdown', this.countdown)
this.countdown -= 1
if (!this.countdown) clearInterval(stopCountdown)
}, 1000)
},
computed: {
formatedCountdown() {
return moment.duration(this.countdown, 'seconds').format('m:ss')
},
},
}
</script>
Solution 2:[2]
const interval = 1000;
const expected = moment();
expected.add(interval, "milliseconds");
expected.add(10, "seconds");
//create acurate timer between two dates
const timer = setInterval(() => {
//calculate the difference between now and expected
const diff = moment.duration(expected.diff(moment()));
if (diff < 0) {
clearInterval(timer);
this.status = "none";
}
//format diff to minutes:seconds
this.timeRemainingToEnd = moment.utc(diff.asMilliseconds());
}, interval);
Don't forget to add the interval timer or the timer will start earlier
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | hamon |
