Stop for loop using break on click

Clash Royale CLAN TAG#URR8PPP
Stop for loop using break on click
I have this simple loop from 1-20, what I'm trying to do is to stop the loop using button click. What I did is, I put a condition that after I click the button the variable stop will change its value to 1, then it will trigger the break. But it doesn't change the value.
stop
break
Thanks, hope you understand me.
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>
add a
console.log(i) before your setTimeout you'll see what I mean– kevinSpaceyIsKeyserSöze
37 mins ago
console.log(i)
setTimeout
if I change my if statement to this
if (i === 3) break; it work.– user123
36 mins ago
if (i === 3) break;
Yes because then you're breaking the loop on 3
– kevinSpaceyIsKeyserSöze
36 mins ago
That's what I'm trying to do break the loop
– user123
30 mins ago
5 Answers
5
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 setInterval is executing.
setTimeout
stop
setInterval
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>
I see, thanks for this sir.
– user123
28 mins ago
the variable still doesn't change.
– user123
25 mins ago
Are you referring to the
stop variable? I added console.log(stop) right before the if check. You can see it changes to 1. Of course, the functions are still executing because we set their timeout right at the beginning.– Maor Refaeli
23 mins ago
stop
console.log(stop)
if
yes sir, you're right. I'm just wondering why the value of stop, doesn't change.
– user123
20 mins ago
I'm afraid I don't understand. It changes if you press on the stop button. If it did not change you would still see new numbers appearing.
– Maor Refaeli
18 mins ago
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
$('ul').append('<li>'+ i +'</li>');
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>
The issue is that the entire for loop has executed before you even had a chance at pressing the button. setTimeout doesn't actually sleep or block, but rather puts a new event and just continues in the for loop.
The browser, all its clocks for timeout purposes and so on can only run when your code has finished running for the time being. There is no thing equivalent to the sleep() function.
Maybe using async functions (ES2015 IIRC, should be supported by all current non-IE browsers), and awaiting for a promise created by util.promisify(setTimeout)(2000) can be more intuitive.
util.promisify(setTimeout)(2000)
There are no blocking functions. There is no sleeping inside code. All code basically runs on the CPU and sets up I/O and timer events which happen asynchronously, once the synchronous part has already finished.
JavaScript is unintuitive for this reason. However you may feel the value for asynchronicity once you have seen that you can get one kind performance this way. I mean... While JS code itself is executing the DOM cannot be checked by the browser. You cannot scroll, you cannot click, the mouse cursor itself won't change its kind. Only once a code block has finished will the browser handle all the pending events.
You can't stop a for loop by a click event because JavaScript is single threaded. The loop beginning
for(let i = 1; i <= 20; i++){
...
runs synchronously when executed without being interrupted by event handlers.
It will initiate 20 timer calls to be executed 500ms apart and return to the event loop before a click handler executes.
You have options to initiate the timer calls anyway and check the stop flag before adding an element, or set up some kind of asynchronous loop (e.g using setInterval) that increments the i variable and stops the timer callback if i reaches a maximum or the click event occurs.
setInterval
i
i
I would do this recursive. Then you have two break conditions stop and count === max.
var stop = false;
var print = function(count, max)
setTimeout(function()
if(stop)
return;
else if(count === max)
return;
else
$('ul').append('<li>'+ count +'</li>');
return print(++count, max);
, count * 500);
$('button').click(function()
stop = 1;
);
print(0, 20);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
<br>
<button>stop</button>
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
because your setTimeout are all triggered already
– kevinSpaceyIsKeyserSöze
38 mins ago