vue定时器实现逻辑
vue定时器实现逻辑
在Vue中实现定时器功能通常涉及setInterval和setTimeout,但需注意组件生命周期内的清理工作以避免内存泄漏。以下是具体实现方法:
基础定时器实现
使用setInterval创建周期性定时任务:
export default {
data() {
return {
timer: null,
counter: 0
}
},
mounted() {
this.timer = setInterval(() => {
this.counter++
console.log('Tick:', this.counter)
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
单次延迟执行
使用setTimeout实现延迟单次执行:
export default {
methods: {
delayedAction() {
setTimeout(() => {
console.log('执行延迟操作')
}, 3000)
}
}
}
组合API实现(Vue3)
在setup()中使用ref管理定时器:
import { ref, onMounted, onUnmounted } from 'vue'
export default {
setup() {
const timer = ref(null)
const count = ref(0)
onMounted(() => {
timer.value = setInterval(() => {
count.value++
}, 1000)
})
onUnmounted(() => {
clearInterval(timer.value)
})
return { count }
}
}
注意事项
- 清理时机:必须在
beforeDestroy(Vue2)或onUnmounted(Vue3)中清除定时器 - 页面隐藏处理:考虑使用
visibilitychange事件暂停后台定时任务 - 误差修正:长时间运行的定时器建议用系统时间差值校准
- 替代方案:复杂场景可考虑
requestAnimationFrame或第三方库如timetask.js
高级场景示例
实现可暂停/恢复的定时器:
export default {
data() {
return {
timer: null,
counter: 0,
isActive: false
}
},
methods: {
start() {
if (!this.isActive) {
this.timer = setInterval(() => {
this.counter++
}, 1000)
this.isActive = true
}
},
pause() {
clearInterval(this.timer)
this.isActive = false
}
}
}






