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