54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import { defineStore } from 'pinia'
|
|
|
|
const BASE_TIMER = 10
|
|
interface state {
|
|
timer_el: any,
|
|
timer_func: any,
|
|
is_enabled: boolean,
|
|
seconds_left: number
|
|
}
|
|
export const useTimer = defineStore('timer', {
|
|
state: () => {
|
|
return {
|
|
timer_el: undefined,
|
|
timer_func: undefined,
|
|
is_enabled: false,
|
|
seconds_left: BASE_TIMER
|
|
} as state
|
|
},
|
|
actions: {
|
|
startTimer() {
|
|
this.is_enabled = true
|
|
clearInterval(this.timer_el)
|
|
this.resetTimer()
|
|
this.timer_el = this.countdownTimer()
|
|
},
|
|
stopTimer() {
|
|
this.is_enabled = false
|
|
|
|
if (this.timer_func) {
|
|
this.timer_func()
|
|
this.startTimer()
|
|
}
|
|
},
|
|
resetTimer() {
|
|
this.seconds_left = BASE_TIMER
|
|
},
|
|
setTimer(time: number) {
|
|
this.seconds_left = time
|
|
},
|
|
countdownTimer() {
|
|
const id = setInterval(() => {
|
|
if (this.is_enabled && this.seconds_left > 0) {
|
|
this.seconds_left -= 1
|
|
// this.countdownTimer()
|
|
}
|
|
if (this.is_enabled && this.seconds_left == 0) {
|
|
this.stopTimer()
|
|
}
|
|
}, 1000)
|
|
return id
|
|
},
|
|
}
|
|
})
|