Skip to content

Instantly share code, notes, and snippets.

@davision
Last active May 3, 2024 13:22
Show Gist options
  • Save davision/3a364a3c3a25a89457dfdc346a7da0a1 to your computer and use it in GitHub Desktop.
Save davision/3a364a3c3a25a89457dfdc346a7da0a1 to your computer and use it in GitHub Desktop.
Simple countdown component for VueJS 2
<template lang="html">
<div v-if="isEnded">
Ended.
</div>
<div v-else>
<div>Days: {{ days }}</div>
<div>Hours: {{ hours }}</div>
<div>Minutes: {{ minutes }}</div>
<div>Seconds: {{ seconds }}</div>
</div>
</template>
<script>
export default {
props: {
endDate: {
type: Date // Date.parse(this.endDate)
}
},
data () {
return {
days: null,
hours: null,
minutes: null,
seconds: null,
isEnded: null
}
},
methods: {
updateRemaining (distance) {
this.days = Math.floor(distance / (1000 * 60 * 60 * 24))
this.hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
this.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
this.seconds = Math.floor((distance % (1000 * 60)) / 1000)
},
tick () {
const currentTime = new Date()
const distance = Math.max(this.endDate - currentTime, 0)
this.updateRemaining(distance)
if (distance === 0) {
clearInterval(this.timer)
this.isEnded = true
}
}
},
mounted () {
this.tick()
this.timer = setInterval(this.tick.bind(this), 1000)
},
destroy () {
clearInterval(this.timer)
}
}
</script>
// Special thanks to Goran Kordun for his help
Copy link

ghost commented Jul 31, 2019

Thanks, just what I need to know.

@davision
Copy link
Author

davision commented Aug 1, 2019

You're welcome! 👍

@vpkopylov
Copy link

Thanks! Simple and useful.

@ondra151
Copy link

Can I get an example of a set end date? Now it gives me NaN in the date.

Thanks

@felloz
Copy link

felloz commented Dec 27, 2022

Can I get an example of a set end date? Now it gives me NaN in the date.

Thanks

Same question here.

@davision
Copy link
Author

davision commented Jan 3, 2023

It is a long time ago, but from the code I think you have to pass a parsed date to the endDate prop, like so: <vue2-countdown :endDate="Date.parse(yourEndDate)"> Let me know if that works for you. @felloz and @ondra151

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment