Jquery SetInterval Loop завершить снова цикл перезапустить - PullRequest
0 голосов
/ 24 декабря 2018

Как заставить цикл продолжения после выполнения определенного условия? Я имею в виду необходимость повторного запуска цикла после достижения определенного значения условия или диапазона.

Jquery setinterval loop условие перезапускается после выполнения определенного условия, нониже мой код не работает, даже не перезапускается.

//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 не перезапускается снова, если выполняется условие.

Ответы [ 2 ]

0 голосов
/ 24 декабря 2018

не перезапускается, потому что вам нужно позвонить autoCheckPagination(), когда pageCount == 3

else if (pageCount == 3) {
  pageCount = 1;
  clearInterval(this.interval);
  this.running = true;
  autoCheckPagination(); // call it again here
}
0 голосов
/ 24 декабря 2018

Я бы порекомендовал использовать 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>
...