gpt4 book ai didi

javascript - 如何为这个基于 setInterval 的 Sprite 动画添加 5 秒延迟?

转载 作者:行者123 更新时间:2023-12-01 01:18:14 25 4
gpt4 key购买 nike

我有一个使用 setInterval 方法运行的 Sprite ,它一直运行,并每隔 60 毫秒将 css 背景位置 (x) 移动 100/(图像数量 -1)。当位置达到 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()

最佳答案

当您将 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();
}

关于javascript - 如何为这个基于 setInterval 的 Sprite 动画添加 5 秒延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54506739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com