我怎么能延迟5秒到这个基于setInterval的精灵动画?

问题描述 投票:0回答:2

我有它运行使用setInterval方法精灵,它运行所有的时间和通过60ms的每间隔100 /(图像的数量-1)移动的CSS背景位置(x)。当位置命中96%我就重置为0简单。这是与动画百分比的sprite公式。

现在,我只想补充每次运行之间有5秒的延迟(每次点击96%x位置时,等待5秒钟,然后再次运行)。什么是实现这一目标的最简单的方法。我试图在另一组间隔包裹的setInterval但这里的问题是,只运行它更多的时候(并使其发疯)。我知道还有一种称为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()
javascript html css-sprites
2个回答
1
投票

也许当您转换您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();
} 

1
投票

您可以添加外部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>
© www.soinside.com 2019 - 2024. All rights reserved.