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

Asked

Viewed 2,088 times

1

I did the implementation of the code below, it rotates the page every X Seconds, but it never stops, it sits in an infinite loop.

I would like to stop the code from running when:

if (track_click >= total_pages - 1) {}

But I don’t know which code to put to stop the 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>
  • There’s already a line in your code that does that: clearInterval(funcaoTimer);. But I haven’t looked at the code in detail, so I can’t tell if this is being used in the right place.

  • The worst I’ve seen, for me is in the right place, but it didn’t work, you can help me ?

  • I entered thus: clearInterval(function Timer);, but the code still works after I asked to interrupt...

  • Maybe the right place to put this (by the way, the whole if (track_click >= total_pages - 1)) be shortly after the track_click++; inside the callback of the $.post.

1 answer

2


Remove the condition:

if (track_click >= total_pages - 1)

of within of condition:

if (track_click <= total_pages){

If this were a show synchronous, it would be all right, but as it is asynchronous it is possible that the track_click be increased twice between one function invocation and another - causing the if internal never run. This should fix the problem of infinite loop, meanwhile I have a strong suspicion that your code has more problems than that:

  • Your line $('#animation_image').load("exportar_4_detalhe.php", ... runs with track_click equal to zero, and at the end increment it to a.
    • If this occurs in less than 1 second, the first invocation of funcaoTimer will request the page 1; otherwise she will order the page 0!
    • Worse: if the first request takes more than 1 and less than 2 seconds, and the second takes least of 1 second, the funcaoTimer will ask for the page 0, and then the page 2 (she will never ask the 1).
  • In any situation that the post take more than a second to complete, the setInterval will cause him to be tempted again, with the same page; this means that the same page can be updated twice, causing a race condition (i.e. even if the page is ok, the track_click will be incremented twice by skipping a page as in the previous case).

Your code accurate be refactored, and I have some suggestions for doing so. Assuming (as stated in the commentary) that the pages should be searched in the order, and that it is not necessary to wait 1 second between one and the other, a viable means would be to request the page N in the proper callback 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!');
    }
}
  • Thanks, for the great help... Are you interested in improving this code for me? [email protected]

  • @I’m sorry, I don’t understand what you mean. I offered to edit my reply by adding a refactoring suggestion, but for that I need those details I asked. For there are several ways to do this, each with its pros and cons (e.g., fire each request at the callback of the previous; trigger multiple requests simultaneously, but with throttling; keep the logic more or less as it is, but eliminating the running condition).

  • I wonder how much you’d charge to get the code right

  • I’m going to email you... [email protected]

  • Friend, you can contact me by email at [email protected]? It would be like?

  • Whoa, slow down! : ) If you want a helping hand to solve this particular problem, I do it right here in this answer, for free... But if it’s something more complex, I’m afraid I don’t provide that kind of service.

  • Friend, what I need is to implement this code, to only as per your suggestion: I need the page N to be ordered only after the N-1 is ready, that is to say the page has been successfully displayed, so yes it can order the subsequent page. Thanks for your help...

  • @Daniloramon Blz, I’m leaving for lunch now, and I’ll update my response with my suggestion. But as for the time of the request, you really need to wait 1 second between one and the other, or you can start the N as soon as the N-1 has arrived?

  • That’s right... I think it’s even better...rs

  • @Daniloramon There it is! I assumed that the first page is 0 and the last page is total_pages. If this is incorrect (e.g., if the last page is total_pages - 1) change the stop condition (the if in proximaPagina). Also, when there is error in the request you have two options: 1) Do nothing; 2) Try again the same page after 1 second. See the comment inside the part with fail.

  • It has to show to me in the code, because I know php, but java I’m even lay.

    1. That one if (track_click <= total_pages){ will enter if track_click is equal to total_pages - making a request for this page. If the last page is total_pages - 1, swap the <= for <. 2) Uncompromisingly setTimeout(proximaPagina, 1000); if you want to try a failed request again after 1 second (beware, if it fails repeatedly, it will show a alert per second!).
  • we can talk by skype, and then post the resolution here. It might be the night at a better time for you ? It might be like this ?

  • 3

    If you have more questions, either open a separate question or ask on [chat]. I’m sorry I can’t pay more attention to your problem, but there are more people in need of help, and I’m just a volunteer here, out of many...

  • I got the code right, now there’s just another question, which I didn’t quite understand in the comment, not for a while. [link]http://answall.com/questions/55050/n%C3%A3o-execute-script-by-time-e-sim-by-execu%C3%A7%C3%A3o-do-script[/link]

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.