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

如何在jQuery中为精灵动画的每个循环结束后设置延迟?

为精灵动画添加循环结束延迟的实现方案

我希望为精灵动画设置2-3秒的延迟,如何在每个循环结束时暂停,随后从初始状态继续播放?我使用以下代码实现了无结束延迟的循环动画:

原实现代码

JavaScript

var imgWidth = 48;
var numImgs = 60;
var cont = 0;

var animation = setInterval(function() {
  var position = -1 * (cont * imgWidth);
  $('#container').find('img').css('margin-left', position);

  cont++;
  if (cont == numImgs) {
    cont = 0;
  }
}, 18);

CSS

#container {
  width: 48px;
  height: 48px;
  display: block;
  overflow: hidden;
}

#container img {
  width: 2880px;
  height: 48px;
}

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <img src="https://visualcraftsman.com/doh/rdWaitAll.png" alt="My super animation" />
</div>

修改方案

核心逻辑是:当动画播放完一轮所有帧时,先停止当前定时动画,通过setTimeout设置2-3秒延迟,延迟结束后重新启动动画并重置计数器。

修改后的完整代码如下:

JavaScript

var imgWidth = 48;
var numImgs = 60;
var cont = 0;
// 自定义延迟时长(单位:毫秒),这里设为2500即2.5秒
var loopDelay = 2500;
var animation;

// 封装动画启动逻辑
function startAnimation() {
  animation = setInterval(function() {
    var position = -1 * (cont * imgWidth);
    $('#container').find('img').css('margin-left', position);

    cont++;
    // 判断是否播放完一轮
    if (cont === numImgs) {
      // 停止当前动画
      clearInterval(animation);
      // 重置帧计数器
      cont = 0;
      // 延迟指定时长后重新启动动画
      setTimeout(startAnimation, loopDelay);
    }
  }, 18);
}

// 初始化启动动画
startAnimation();

CSS(无需修改)

#container {
  width: 48px;
  height: 48px;
  display: block;
  overflow: hidden;
}

#container img {
  width: 2880px;
  height: 48px;
}

HTML(无需修改)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <img src="https://visualcraftsman.com/doh/rdWaitAll.png" alt="My super animation" />
</div>

关键修改说明

  • 将动画逻辑封装到startAnimation函数,方便延迟后重复调用
  • 检测到播放完所有帧时,清除当前定时器并重置计数器
  • 通过setTimeout实现循环结束后的暂停,可调整loopDelay变量设置2-3秒之间的任意延迟(如2000为2秒,3000为3秒)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:01:44