I have this simple loop from 1-20. What I'm trying to do is to stop the loop using a button click. What I did is, I put a condition that upon button click the value of the variable stop will be changed to 1, which will trigger the break. But the value is not changed.
var stop = 0;
for(let i = 1; i <= 20; i++){
if(stop === 1){
break;
}
setTimeout(function(){
$('ul').append('<li>'+ i +'</li>');
},i * 500);
}
$('button').click(function(){
stop = 1;
});
ul li{
list-style-type: none;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
<br>
<button>stop</button>
The 20 setTimeout functions were called before you even pressed on stop.
One of many ways to fix this is to check the stop variable inside the function setTimeout is executing.
var stop = 0;
for (let i = 1; i <= 20; i++){
setTimeout(function(){
console.log(stop);
if (stop !== 1) {
$('ul').append('<li>'+ i +'</li>');
}
},i * 500);
}
$('button').click(function(){
stop = 1;
});
ul li{
list-style-type: none;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
<br>
<button>stop</button>
Edit:
You ask how to stop the for loop. The way it's written you can't.
This is how I would have implemented this in order to "stop" the loop with setTimeout.
You can also do it with setInterval (check Сергей Петрашко's answer to see a how).
Read about the differences between them here):
var stop = false;
function addNumberAndCallNext(number, max) {
if (!stop && number <= max) {
$('ul').append('<li>'+ number +'</li>');
setTimeout(addNumberAndCallNext.bind(null, ++number, max), 500);
}
}
addNumberAndCallNext(1, 20);
$('button').click(function(){
stop = true;
});
ul li {
list-style-type: none;
float: left;
padding-right: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
<br>
<button>stop</button>
You can try next code without jQuery.
I don't recomend to use --- $('ul').append('<li>'+ i +'</li>'); -
is bad practice.
true way --is create node before loop.
in this task you can use setIntrval instead of setTimout and loop
let itemList = (i) => {
let item = document.createElement('li');
item.value = i;
item.textContent = i;
return item;
}
let list = document.getElementById('list');
let stopButton = document.getElementById('stop');
let i = 0,
interval;
let reset = () => {
clearInterval(interval)
}
stopButton.addEventListener('click', () => {
reset()
});
interval = setInterval(() => {
list.append(itemList(i))
i++;
if (i > 20) reset()
}, 300)
<button id="stop">stop</button>
<br>
<ul id="list"></ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With