Move current time tracker to Pinia

This commit is contained in:
Matt Isenhower
2022-05-08 20:38:29 -07:00
parent 5f22afb68d
commit 8a4ef94bed
2 changed files with 44 additions and 16 deletions

View File

@@ -26,30 +26,22 @@
</template>
<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { computed, onMounted, onUnmounted } from 'vue';
import { useTimeStore } from '../stores/time';
const announceDate = new Date('2021-02-17');
const releaseDate = new Date('2022-09-09');
const now = ref(new Date);
const time = useTimeStore();
let timer;
onMounted(() => {
timer = setInterval(() => {
now.value = new Date;
}, 200);
})
onUnmounted(() => clearInterval(timer))
onMounted(() => time.startUpdatingNow());
onUnmounted(() => time.stopUpdatingNow());
const totalTime = releaseDate - announceDate;
const remainingTime = computed(() => {
let time = now.value.getTime();
// Adjust the time based on midnight local time
let adjustment = (new Date).getTimezoneOffset() * 60 * 1000;
// Compare the time based on midnight local time
time -= (new Date).getTimezoneOffset() * 60 * 1000;
return releaseDate - time;
return releaseDate - time.now + adjustment;
})
const completedTime = computed(() => totalTime - remainingTime.value);
const percent = computed(() => Math.min(100, 100 * completedTime.value / totalTime));

36
src/stores/time.js Normal file
View File

@@ -0,0 +1,36 @@
import { defineStore } from 'pinia'
function now() {
let time = (new Date).getTime();
// We only need the time to be accurate to one second
return Math.trunc(time / 1000) * 1000;
}
let timer;
export const useTimeStore = defineStore('time', {
state: () => ({
now: now(),
}),
actions: {
updateNow() {
this.now = now();
},
startUpdatingNow() {
if (!timer) {
timer = setInterval(() => {
// Reduce noise on the devtools timeline
// by only updating when we need to.
if (this.now !== now()) {
this.updateNow();
}
}, 200);
}
},
stopUpdatingNow() {
clearInterval(timer);
timer = null;
},
},
});