Infinite Loop. How to stop the Loop in a certain situation?

1

I've implemented the code below, it runs the page every X Seconds, but it never stops, it gets in an infinite loop.

I would like to make the code stop running when:

if (track_click >= total_pages - 1) {}

But I do not know what code to put to stop script execution.

  <script type="text/javascript">

    var track_click = 0; 
    var total_pages = <?php echo $total_pages; ?>;

    $('#animation_image').load("exportar_4_detalhe.php", {'page': track_click}, function() {
        track_click++;
    });

    var funcaoCounter = 0;
    var funcaoTimer = setInterval(function(){
        funcaoCounter++;

            $('.load_more').hide();
            $('.animation_image').show(); 



            if (track_click <= total_pages){

                $.post('exportar_4_detalhe.php', {'page': track_click}, function(data) {

                    $(".load_more").hide();

                    $("#results").append(data);

                    var resultado = ( track_click /total_pages ) * 100;
                    // document.title = track_click + " de " + total_pages;

                    var new_num = resultado.toFixed(2);

                    var new_num = new_num + "%";

                    document.title = new_num;

                    $('.porcentagem').text(new_num);

                    $("html, body").animate({scrollTop: $("#animation_image").offset().top}, 500);

                    $('.animation_image').hide();

                    track_click++;

                }).fail(function(xhr, ajaxOptions, thrownError) {
                    alert(thrownError); 
                    $(".load_more").show();
                    $('.animation_image').hide(); 
                });


                if (track_click >= total_pages - 1)
                {
                     $('.animation_image').hide(); 
                     clearInterval(funcaoTimer);
                     alert('Todos os Registros forma Exibidos!');

                }
            }

}, 1000);

</script>
    
asked by anonymous 18.03.2015 / 22:09

1 answer

2

Remove condition:

if (track_click >= total_pages - 1)

of within condition:

if (track_click <= total_pages){

If this was a synchronous program, that would be fine, but since it is asynchronous it is possible that track_click is incremented twice between a function invocation and other - causing% internal% to never be executed. This should fix the problem of the infinite loop, however I have a strong suspicion that your code has more problems than this:

  • Its if line runs with $('#animation_image').load("exportar_4_detalhe.php", ... equal to zero, and at the end increments it to one.
    • If this occurs in less than 1 second, the first invocation of track_click will request the funcaoTimer page; otherwise, it will request the page 1 !
    • Worst: If the first request takes more than 1 and less than 2 seconds, and the second one takes less than 1 second, 0 will request the funcaoTimer page, and then the page 0 (it will never ask the 2 ).
  • In any situation that 1 takes more than a second to complete, post will cause it to try again, with the same page ; this means that the same page can be refreshed twice, causing a race condition (i.e. even though the page is ok, setInterval will be incremented twice by skipping a page just like in the previous case).

Your need code to be refactored, and I have some suggestions for doing so. Assuming (as stated in the comment) that the pages should be searched in order, and that it is not necessary to wait 1 second between one and another, a viable means would be to make the request to page N in the callback of the page N-1. Example:

var track_click = 0; 
var total_pages = <?php echo $total_pages; ?>;

$('#animation_image').load("exportar_4_detalhe.php", {'page': track_click}, function() {
    track_click++;
    proximaPagina();
});

function proximaPagina() {
    $('.load_more').hide();
    $('.animation_image').show();

    if (track_click <= total_pages){ // Nota: "<=" ou "<"?

        $.post('exportar_4_detalhe.php', {'page': track_click}, function(data) {

            $(".load_more").hide();
            $("#results").append(data);

            var resultado = ( track_click /total_pages ) * 100;
            // document.title = track_click + " de " + total_pages;

            var new_num = resultado.toFixed(2);
            var new_num = new_num + "%";
            document.title = new_num;
            $('.porcentagem').text(new_num);

            $("html, body").animate({scrollTop: $("#animation_image").offset().top}, 500);
            $('.animation_image').hide();

            track_click++;
            proximaPagina(); // Chama de novo pra próxima página, ou para concluir

        }).fail(function(xhr, ajaxOptions, thrownError) {
            alert(thrownError); 
            $(".load_more").show();
            $('.animation_image').hide(); 

            // POSSIBILIDADE: tentar de novo após 1s quando houver falha
            // (descomente para habilitar)
            // setTimeout(proximaPagina, 1000); // Tenta de novo a mesma página
        });
    }
    else {
        $('.animation_image').hide(); 
        alert('Todos os Registros forma Exibidos!');
    }
}
    
19.03.2015 / 03:55