为什么setTimeout不能在for循环中工作?我正在尝试将一个类添加到每个帧中,一次一个,每三秒我需要从当前帧中删除它,并将其添加到下一个帧中。当它到达第6帧时,我需要它在删除类之前等待10秒。然后我需要所有的重复。但它只是直接将类添加到所有这些类中,而不是删除它们。
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>
发布于 2018-02-06 19:00:58
你的代码有两个问题。首先,您期望在创建下一个超时之前执行超时,这是错误的。你可以同时创建它们。其次,您在超时中重用了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>
https://stackoverflow.com/questions/48641296
复制相似问题