gpt4 book ai didi

javascript - 在循环末尾添加暂停

转载 作者:行者123 更新时间:2023-12-02 16:04:34 25 4
gpt4 key购买 nike

下面的代码工作正常,直到我尝试在其中添加暂停。基本上,它会循环并看起来很正常,但几次之后它就会追上自己并导致很多奇怪的结果。我很好奇是否有更好的方法来实现我的目标。

var popups = $('.animate');
var i = 0;
var pT = 2000;

function animatePopup() {
if (i >= popups.length){
i = 0;
}
popups.eq(i).addClass("show")
.delay(2000)
.queue(function() {
$(this).removeClass("show");
$(this).dequeue();
if (i == popups.length) {
setInterval(animatePopup, pT);
} else {
animatePopup();
}
});
i++;
}
animatePopup();

最佳答案

使用setTimeout而不是setInterval

setInterval 按时间间隔运行代码/函数,其间有超时长度,但它保持运行。另一方面,setTimeout 在指定时间结束时运行一次

这是一个片段,如果您将 setTimeout 更改回 setInterval,您会发现它也会变得疯狂

function recurrentDelayedFunction() {

$('#out').append('ran<br>');

setTimeout(recurrentDelayedFunction, 2000);
}

recurrentDelayedFunction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id=out></div>

关于javascript - 在循环末尾添加暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30894496/

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