如何为这个基于 setInterval 的精灵动画添加 5 秒的延迟?

How can I add a 5 second delay to this setInterval based sprite animation?

我有一个使用 setInterval 方法 运行s 的精灵,它一直 运行s 并且将 css 背景位置 (x) 移动 100/(number of images -1) 每 60ms 的间隔。当位置达到 96% 时,我将其重置为 0。很简单。这是使用百分比为 sprite 设置动画的公式。

现在我只想在每次 运行 秒之间添加 5 秒的延迟(每次它达到 96% x 位置时,等待 5 秒然后再次 运行)。实现此目的的最简单方法是什么。我尝试将 setInterval 包装在另一个设置的间隔中,但这里的问题是只有 运行s 它更频繁(并使其变得疯狂)。我知道还有一种叫做 clearInterval 的方法,我想也许每隔几秒使用一次就可以了,但是之后我该如何重新启动动画呢?我需要它 运行 一遍又一遍,每次 运行.

之间有 5 秒的延迟
    function animateAlways() {

        var positionHeadDot = 0;
        var interval = 60;
        const diffHeadDot = 3.703704;


        shadeSparkle = setInterval(() => {
            /////////////////////HeadDot////////////////////////////////////
            document.getElementById("imageHeadDot").style.backgroundPosition =
                `${positionHeadDot}% 0%`;
            if (positionHeadDot < 96) {

                positionHeadDot = positionHeadDot + diffHeadDot;

            }
            else {

                positionHeadDot = 0;

            }
        }, interval); 

    } 

    animateAlways()

setInterval 代码转换为使用 setTimeout 可能会更容易。然后你可以区分进度和最终步骤并提供调整后的超时值:

function animateAlways() {
    var positionHeadDot = 0;
    var interval = 60;
    var delay = 5000;
    const diffHeadDot = 3.703704;

    function animate() {
        /////////////////////HeadDot////////////////////////////////////
        document.getElementById("imageHeadDot").style.backgroundPosition =
            `${positionHeadDot}% 0%`;
        if (positionHeadDot < 96) {
            positionHeadDot = positionHeadDot + diffHeadDot;
            setTimeout(animate, interval);
        }
        else {
            positionHeadDot = 0;
            setTimeout(animate, delay); // 5 second wait.
        }
    }
    animate();
} 

您可以添加一个外部 setInterval,然后使用 clearInterval 清除内部间隔而不是将位置设置回 0:

function animateAlways() {
  var positionHeadDot = 0;
  var interval = 60;
  const diffHeadDot = 3.703704;

  shadeSparkle = setInterval(() => {
    /////////////////////HeadDot////////////////////////////////////
    document.getElementById("imageHeadDot").style.backgroundPosition =
      `${positionHeadDot}% 0%`;
    if (positionHeadDot < 96) {
      positionHeadDot = positionHeadDot + diffHeadDot;
    } else {
      clearInterval(shadeSparkle);
    }
  }, interval);
}

animateAlways();
setInterval(animateAlways, 5000);
#imageHeadDot {
  background-image: url('https://www.w3schools.com/CSSref/smiley.gif');
  width: 600px;
  height: 50px;
  border: 3px solid black;
}
<div id="imageHeadDot"></div>