Skip to content Skip to sidebar Skip to footer

Javascript: Exit From Javascript Loop When Button Clicked

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;

Solution 1:

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);
});

Post a Comment for "Javascript: Exit From Javascript Loop When Button Clicked"