0

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.

1
  • use event.preventDefault or return false; Commented Dec 28, 2012 at 8:30

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.