我有一个使用setInterval方法运行的精灵,它始终运行,每60ms的间隔将css背景位置(x)移动100 /(图像数量-1)。当位置达到96%时,我将其重置为0。很简单。这是用百分比动画精灵的公式。

现在,我只想在每次运行之间添加5秒的延迟(每次达到96%x位置时,请等待5秒钟然后再次运行)。实现此目的最简单的方法是什么。我尝试将setInterval包装在另一个set间隔中,但是这里的问题是它只会更频繁地运行(并使它发疯)。我知道还有一种叫做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();
}

09-20 23:54