You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用setTimeout时Web Animations API动画进度不符合预期的问题

解决Web Animations API获取动画进度不正确的问题

你遇到的这个问题很典型——用 animation.effect.getComputedTiming().progress 拿不到预期的播放进度,核心原因是这个属性并非用来获取动画实时播放进度的正确方式。

正确的解决方案

你需要通过 animation.currentTime(动画当前已播放的毫秒数)除以动画总时长来计算进度:

const animation = div.animate({ opacity: 0 }, { duration: 2000 });
setTimeout(() => {
  const timing = animation.effect.getComputedTiming();
  const progress = animation.currentTime / timing.duration;
  console.log(progress); // 此时会输出约0.5,符合预期
}, 1000);

为什么原来的方法不行?

effect.getComputedTiming().progress 对应的是动画效果本身的内部进度,它更多关联动画的迭代逻辑、填充模式等配置,并不会实时反映当前播放的时间进度。而 animation.currentTime 是Web Animations API专门提供的、用于获取动画当前播放位置的属性,会随着动画运行实时更新,用它除以总时长就能得到准确的0-1范围进度值。

额外注意事项

如果你的动画可能被暂停、取消或带有延迟,建议先判断动画播放状态,避免计算出错:

const animation = div.animate({ opacity: 0 }, { duration: 2000 });
setTimeout(() => {
  if (animation.playState === 'running') {
    const timing = animation.effect.getComputedTiming();
    const progress = animation.currentTime / timing.duration;
    console.log(progress);
  } else {
    console.log("动画未处于运行状态,无法获取进度");
  }
}, 1000);

内容的提问来源于stack exchange,提问作者Ezys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:22:35