Reputation: 91
I've a javascript loop that call by ajax a php function. I need to stop that loop by clicking a button. I tried using labels but it's not possible:
labelName:
for (var counter = 0; counter <= 1000; counter++) {
...
ajax call
...
}
$('#button-stop').click(function(event) {
event.preventDefault();
break labelName;
});
But this make error "SyntaxError label not found". In fact only if I put "break labelName;" into loop error disappears. But if I put that into click function not recognize label again.
How I can make that? Is any other way to break a loop by a button interaction? Thanks.
Upvotes: 0
Views: 2016
Reputation: 4077
You are not able to stop the cycle this way. When the button is clicked, 'click event' is put into event loop and it will be executed only after the cycle finishes. So, in your variant, a thousand requests will be sent to a server anyway.
If you want to control message sending to the server, it is better to use intervals:
var sender = setInterval(function() {
//ajax here
}, 1000);
$('#button-stop').click(function(event) {
clearInterval(sender);
});
Upvotes: 2