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>