I am attempting to set up a button event in Vue 3 that displays a setTimeout countdown on the button before routing to another page. My event function includes a conditional that executes a countdown from 5 to 0 when the countValue is > 0. The setTimeout function is recursive in that it calls the goHome() function each time to execute a countdown. When the countValue is 0, then router.push is called to re-route to another page. My issue is that when I press the button, the countdown immediately lumps from 5 to 4. I am wanting to briefly delay the countdown when I first push the button. In other words, I do not want the countdown to immediately jump to 4 when I push the button. How can I fix this?
Here is my code so far:
Template:
<div>
<button @click="goHome" type="button" :disabled="disabledOnCount === true ? true : false">Go Home in {{ countValue }} seconds</button>
</div>
Script:
import { ref } from '@vue/reactivity'
const countValue = ref(5)
const goHome = () => {
if (countValue.value > 0) {
disabledOnCount.value = true
countValue.value -= 1
setTimeout(() => {
goHome()
if (countValue.value === 0) {
router.push({ name: 'home' })
}
}, 1000)
}
}