![](/img/trans.png)
[英]How to stop a function running after a number of seconds? setTimeout, clearTimeout and setInterval wont work correctly
[英]Run a setInterval function, stop it for 3 seconds and continue running it
我有一个setInterval函数通过某些div类,如果它找到具有特定类的div,则应停止3秒钟,然后继续运行。 注意我如何使用:
clearInterval(myInterval);
但我还需要其他一些东西,以重新开始该序列或使其继续从那里开始运行。
例如:
var myInterval = setInterval(function() {
move.removeClass( "girlFromRight" );
runFromRight -= 9;
move = $("#grid"+ runFromRight);
move.addClass("girlFromRight");
if (move.hasClass("man") === true ||
move.hasClass("man-right") === true ||
move.hasClass("man-left") === true )
{
clearInterval(myInterval);
move.addClass('inLove');
move.removeClass('girlFromRight');
setTimeout(function() {
move.removeClass('inLove');
move.addClass('man');
}, 3000);
}
if (c == 9){
clearInterval(myInterval);
}
}, 300);
keyPressed = false;
}, randomTime);
}
考虑使用setTimeout并根据测试在每次运行后设置间隔(300或3000)。 这样,您不必启动和停止setInterval 。
下面是一个简单的示例,该示例按顺序突出显示每个div,在文本内容被3整除的任何位置上暂停更长的时间(作为示例测试)。
function doLoop(){ var divs = document.querySelectorAll('div'); var i = 0; function loop(){ var selected = document.querySelectorAll('.selected'); [].forEach.call(selected,function(el) { el.className = 'notSelected'; }); divs[i].className = 'selected'; setTimeout(loop, divs[i].textContent % 3? 300 : 3000); i = ++i % (divs.length - 2); } loop(); } window.onload = doLoop;
.notSelected{} .selected{ background-color: blue; }
<div class="notSelected">0</div> <div class="notSelected">1</div> <div class="notSelected">2</div> <div class="notSelected">3</div> <div class="notSelected">4</div> <div class="notSelected">5</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.