开发者

Breaking loop from outside the loop

开发者 https://www.devze.com 2023-01-11 11:52 出处:网络
I have a search form with default values. 开发者_如何学JAVAAs the user loades the page, onload I call a function.

I have a search form with default values. 开发者_如何学JAVAAs the user loades the page, onload I call a function.

This function has a loop, which calls a Ajax Request with each iteration.

I take about 20 to 30 Seconds will all the Ajax Request are executed.

During these Iteration user can change form values and can Submit the form before these iterations are completed.

Is there a way to break that loop as the user clicks on the submit button?

Thanks.


If the form is being posted back, the page will unload. Any pending requests will be dropped (though the server will continue processing any requests that it has already seen, can't help that). If the post happens via AJAX as well, then you could use a guard variable and simply set it before you do the submit and check it before you send off a request for an update.

I'll assume that you want to do periodic updates until the form is submitted -- a loop is not really the ideal way to handle that. The example below uses setTimeout to poll the server every second -- as long as the form hasn't already been submitted.

var submitted = false;
var timer = null;
$('.submit-button').click( function() {
    submitted = true;
    if (timer) clearTimeout( timer );
    $('form').submit();
    return false;
});

function doUpdate()
{
     if (!submitted) {
         $.ajax({
            ...
         });
         timer = setTimeout(doUpdate,1000);
     }
}

doUpdate();


Sort of, before each ajax request is called, have it check for a flag. Say for example it could be intiialised on page load as CARRY_ON = true;

Now when the submit button is pressed, change the flag to false. Then all future ajax requested will be stopped.


When you will submit the form, automatically other client side execution will be terminated.

If you submit using Ajax, then you can keep a flag (global variable) to stop the loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消