vue实现定时效果
使用 setInterval 实现定时器
在 Vue 中可以通过 setInterval 实现定时效果,适用于周期性任务。在组件的 mounted 钩子中启动定时器,并在 beforeDestroy 钩子中清除,避免内存泄漏。
export default {
data() {
return {
timer: null,
count: 0
}
},
mounted() {
this.timer = setInterval(() => {
this.count++
console.log('定时执行', this.count)
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
使用 setTimeout 实现单次延迟
setTimeout 适用于单次延迟执行任务。同样需要在组件销毁时清除定时器。

export default {
data() {
return {
timeout: null
}
},
mounted() {
this.timeout = setTimeout(() => {
console.log('延迟执行')
}, 2000)
},
beforeDestroy() {
clearTimeout(this.timeout)
}
}
使用 Vue 的 $nextTick
对于需要等待 DOM 更新后执行的操作,可以使用 $nextTick。该方法会在下次 DOM 更新循环结束后执行回调。
export default {
methods: {
updateMessage() {
this.message = '更新后的消息'
this.$nextTick(() => {
console.log('DOM 已更新')
})
}
}
}
使用第三方库(如 lodash 的 debounce)
对于需要防抖或节流的场景,可以使用 lodash 的 debounce 或 throttle 方法优化性能。

import { debounce } from 'lodash'
export default {
methods: {
handleInput: debounce(function() {
console.log('防抖处理后的输入')
}, 500)
}
}
使用 requestAnimationFrame 实现动画定时
对于动画场景,可以使用 requestAnimationFrame 实现更流畅的定时效果。
export default {
data() {
return {
animationId: null,
position: 0
}
},
methods: {
animate() {
this.position += 1
this.animationId = requestAnimationFrame(this.animate)
}
},
mounted() {
this.animate()
},
beforeDestroy() {
cancelAnimationFrame(this.animationId)
}
}
使用 VueUse 的 useInterval 组合式函数
如果使用 Vue 3 的组合式 API,可以通过 @vueuse/core 提供的 useInterval 简化定时器管理。
import { useInterval } from '@vueuse/core'
export default {
setup() {
const count = ref(0)
const { pause, resume } = useInterval(() => {
count.value++
}, 1000)
return { count, pause, resume }
}
}
注意事项
- 定时器需在组件销毁时手动清除,避免内存泄漏。
- 对于频繁操作(如滚动、输入),优先考虑防抖或节流。
- 动画场景推荐使用
requestAnimationFrame而非setInterval。 - 组合式 API 中可通过
onUnmounted生命周期钩子清除定时器。






