I have Vue 3-pages application with VueRouter. On the first page I asked a server every minute using setTimeout. On move to the next page timer is lost and reinitialized anew on first page open again. I want timer to coninue working in background. Is it possible and how to do it done?
Just put the timer in your root component (e.g., App.vue
), since that component will always exist:
export default {
mounted() {
const pages = [ '/page1', '/page2', '/page3' ]
let currentPage = 0
this._timerId = setInterval(() => {
this.$router.push(pages[currentPage++ % pages.length])
}, 3000) // every 3 seconds
},
// Vue 2
beforeDestroy() {
clearInterval(this._timerId)
},
// Vue 3
unmounted() {
clearInterval(this._timerId)
}
}