gpt4 book ai didi

javascript - 在 for 循环中使用 setTimeout

转载 作者:行者123 更新时间:2023-11-30 20:46:29 27 4
gpt4 key购买 nike

为什么 setTimeout 在 for 循环中不起作用?我正在尝试一次将一个类添加到每个帧中,并且每三秒钟我需要将其从当前帧中删除并将其添加到下一帧中。当它到达第 6 帧时,我需要它等待十秒钟才能删除该类。然后我需要这一切来重复。但它只是立即将类全部添加到它们中,然后不删除它们。

for(i = 1; i < 6; i++){
jQuery('.frame-'+i).addClass('color');

if(i < 6){
setTimeout(function(){
jQuery('.frame-'+i).removeClass('color');
}, 3000);
}else if(i = 6){
setTimeout(function(){
jQuery('.frame-'+i).removeClass('color');
i = 1;
}, 10000);
}
}
.color{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="frame-1">one</div>
<div class="frame-2">two</div>
<div class="frame-3">three</div>
<div class="frame-4">four</div>
<div class="frame-5">five</div>
<div class="frame-6">six</div>

最佳答案

您的代码有 2 个问题。首先,您期望在创建下一个超时之前执行超时,这是错误的。您正在同时创建它们。其次,您在超时内重复使用 i 变量,因此当它们触发时,对于所有这些变量,它都是 6。

但是,你可以创建一个递归函数来处理所有这些,就像这样......

function timeoutHandler(i) {
// if no value is passed, set i = 1
if (!i) i = 1;

// if i < 6 then create a setTimeout for 3 seconds
// when we remove the class and call the function again with i + 1
if (i < 6) {
setTimeout(function() {
$(".frame-" + i).removeClass("color");
timeoutHandler(++i);
}, 3000);
}
// else (i == 6) setTimeout for 10 seconds
// when we remove the class and stop
else {
setTimeout(function() {
$(".frame-" + i).removeClass("color");
}, 10000);
}
}

// add class to initialise - should really do this in html
for(i = 1; i < 7; i++) {
$(".frame-" + i).addClass("color");
}

// start
timeoutHandler();
.color{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="frame-1">one</div>
<div class="frame-2">two</div>
<div class="frame-3">three</div>
<div class="frame-4">four</div>
<div class="frame-5">five</div>
<div class="frame-6">six</div>

关于javascript - 在 for 循环中使用 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48641296/

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