advent22/ui/src/components/CountDown.vue

59 lines
1.3 KiB
Vue
Raw Normal View History

2023-09-15 16:55:03 +00:00
<template>
{{ string_repr }}
</template>
<script lang="ts">
import { Options, Vue } from "vue-class-component";
@Options({
props: {
millis: Number,
tick_time: {
type: Number,
default: 200,
},
},
})
export default class extends Vue {
private millis!: number;
private tick_time!: number;
private interval_id: number | null = null;
public string_repr = "";
private get target_time(): number {
const now_time = new Date().getTime();
return new Date(now_time + this.millis).getTime();
}
private tick(): void {
const now = new Date().getTime();
const distance = new Date(this.target_time - now).getTime();
if (distance <= 0) {
this.string_repr = "Jetzt!";
return;
}
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor(
(distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60),
);
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
this.string_repr = `${days} Tage, ${hours}:${minutes}:${seconds}`;
}
public mounted(): void {
this.tick();
this.interval_id = window.setInterval(this.tick, this.tick_time);
}
public beforeUnmount(): void {
if (this.interval_id === null) return;
window.clearInterval(this.interval_id);
}
}
</script>