如何在满足特定条件后继续循环?我的意思是需要在满足特定条件值或范围后再次重新开始循环。
jquery setinterval循环条件在满足某些条件后重新启动,但低于我的代码,甚至无法重新启动。
//Global interval:any;
<i>public autoCheckPagination(): void {
clearInterval(this.interval);
this.interval=setInterval(function(){
if(pageCount<3){ //loop range till 3
if(count<1){
count=5;
pageNextClick.click();
}
document.getElementById("displayAutoCount").innerHTML = count+"";
count--;
pageCount++;
}else if(pageCount==3){ //loop meet condition again but not restart
restart loop again
pageCount=1;
clearInterval(this.interval);
this.running=true;
}
},1000);
}</i>
如果满足条件,则Setinterval循环不会再次重启。
答案 0 :(得分:1)
如果您要反复遍历一个函数,建议使用setTimeout
。下面的演示为您提供了编写所需功能所需的所有工具。
单击按钮即可开始循环,只有选中复选框后才能继续,单击按钮即可停止循环。
停止循环的功能是独立的,因此您可以通过多种方式或在代码的各个位置调用它。
// Create array for setTimeouts
var timeouts = [];
// Start loop on click of button
$("#startLoop").click(function() {
// Add class that enables scroll
$(this).addClass("show-scroll");
// Stop all other timeouts
var cleared = stopLoop();
// Run your function
yourFunction();
});
// Stop all timeouts when clicking stop loop button
$("#stopLoop").click(function() {
// Stop all other timeouts
var cleared = stopLoop();
console.log("Loop stopped by clicking button");
});
// You master function, that will repeatedly fire
function yourFunction() {
// Demonstrate to user loop is continuing
$("#dots").append(".");
// Check if the checkbox is still checked
if ($('#continueCheck').prop('checked')) {
// Start a new setTimeout to continue loop
timeouts.push(setTimeout(yourFunction, 1000));
} else {
// Stop the loop
stopLoop();
console.log("Loop stopped as checkbox is not checked.");
}
}
// Indepenent function to end all timeouts
function stopLoop() {
// Clear all setTimeouts
for (var i = 0; i < timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="startLoop">Start Loop</button>
<button id="stopLoop">Stop Loop</button>
<input type="checkbox" id="continueCheck" checked/> Continue loop
<hr>
<div id="dots"></div>
答案 1 :(得分:1)
未重新启动,因为您需要在autoCheckPagination()
时呼叫pageCount == 3
else if (pageCount == 3) {
pageCount = 1;
clearInterval(this.interval);
this.running = true;
autoCheckPagination(); // call it again here
}