timeupdate事件是HTML5中监听媒体播放时间最常用方式,周期性触发(约200–250ms一次),需在loadedmetadata后绑定,通过currentTime获取秒级浮点值,用于更新进度条和格式化时间显示。

在 HTML5 中,timeupdate 事件是监听媒体(如 <video></video> 或 <audio></audio>)当前播放时间最常用的方式。它会在播放过程中**周期性触发**(通常每 200–250ms 一次),用于实时更新进度条、显示当前时间等。
确保媒体元素支持并正确绑定事件
必须在媒体元素加载元数据(metadata)后绑定事件,否则可能错过早期触发。推荐使用 loadedmetadata 事件作为安全时机,或直接在元素就绪后绑定(现代浏览器中即使提前绑定也大多能正常工作):
- 用
addEventListener绑定更规范,避免覆盖已有监听器 - 不要依赖
on timeupdate="..."内联写法,不利于维护和复用 - 确保媒体有合法的
src且未被静音/阻塞(如自动播放策略影响)
获取并更新当前播放时间(currentTime)
timeupdate 触发时,可通过媒体元素的 currentTime 属性读取以秒为单位的浮点数值(例如 12.345)。常用于同步 UI:
- 更新自定义进度条的
value或style.width - 格式化显示“分:秒”,如
Math.floor(time / 60) + ':' + ('0' + Math.floor(time % 60)).slice(-2) - 结合
duration计算进度百分比:(video.currentTime / video.duration) * 100
注意性能与精度问题
timeupdate 触发频率高,但不保证精确时间间隔,也不保证每一帧都触发。实际应用中需注意:
立即学习“前端免费学习笔记(深入)”;
- 避免在回调中执行重绘、复杂计算或 DOM 批量操作;可节流(throttle)到 30fps 左右(约 33ms)
-
duration在媒体未加载完成时可能是NaN或Inf,应先判断isFinite(video.duration) - 用户拖动进度条时也会触发
timeupdate,无需额外监听seeking或seeked(除非需要区分场景)
简单可用示例
以下代码可直接运行,实现进度条与时间文本的实时同步:
<video id="myVideo" controls>
<source src="example.mp4" type="video/mp4">
</video>
<progress id="progressBar" max="100" value="0"></progress>
<span id="currentTime">0:00</span>
<p><script>
const video = document.getElementById('myVideo');
const progressBar = document.getElementById('progressBar');
const timeDisplay = document.getElementById('currentTime');</p><p>video.addEventListener('loadedmetadata', () => {
video.addEventListener('timeupdate', () => {
if (isFinite(video.duration)) {
const percent = (video.currentTime / video.duration) * 100;
progressBar.value = percent;
timeDisplay.textContent = formatTime(video.currentTime);
}
});
});</p><p>function formatTime(seconds) {
const min = Math.floor(seconds / 60);
const sec = Math.floor(seconds % 60);
return <code>${min}:${sec < 10 ? '0' : ''}${sec}</code>;
}
</script>



















