如何持续获取HTML Video的当前播放时间?
更优的视频播放时间获取方案
你的思路没错,requestAnimationFrame完全是替代setInterval的更优选择,甚至还有两种更贴合视频场景的方案,下面逐一说明:
方案一:requestAnimationFrame(高精度平滑更新)
setInterval的问题在于固定间隔采样、后台会被节流,且容易遗漏暂停时的清理。requestAnimationFrame和浏览器渲染帧同步,精度更高(约16.6ms/次,对应60fps),且在页面后台时会自动暂停,性能更优。
实现代码:
this.video = document.createElement('video') this.duration = null this.currentTime = null this.rafId = null // 用于存储动画帧ID,方便后续取消 // 绑定事件 this.video.addEventListener('play', this.handlePlay) this.video.addEventListener('pause', this.handlePause) this.video.addEventListener('ended', this.handlePause) // 视频结束时也需要停止更新 handlePlay() { const updateTime = () => { this.currentTime = this.video.currentTime this.rafId = requestAnimationFrame(updateTime) } updateTime() // 立即执行一次,避免首帧延迟 } handlePause() { if (this.rafId) { cancelAnimationFrame(this.rafId) this.rafId = null } }
方案二:timeupdate事件(浏览器优化的事件触发)
如果不需要极致的实时性,直接监听视频的timeupdate事件更省心——这个事件由浏览器在currentTime变化到一定阈值时自动触发,浏览器会根据播放状态优化触发频率,不需要手动管理循环。
实现代码:
this.video = document.createElement('video') this.duration = null this.currentTime = null this.video.addEventListener('timeupdate', () => { this.currentTime = this.video.currentTime }) // 无需额外处理play/pause,浏览器自动管理事件触发
方案对比
- requestAnimationFrame:适合需要平滑、高精度时间更新的场景(比如进度条实时同步),但需要手动管理启动/停止。
- timeupdate:适合对精度要求不高的场景,代码更简洁,无需手动维护循环。
内容的提问来源于stack exchange,提问作者Math
相关产品推荐
相关产品推荐

