Airikr
Airikr

Reputation: 6436

AJAX: Reload load() on error after X seconds

I use the following function to get information from a file with load(). If the content doesn't load as it should, will it show a error message. This works perfectly but I want to reload the request after X seconds. I have done this far:

var tick = function() {
    $('#fetch-1').hide();
    $('#fetch-2').hide();
    $('#fetch-3').hide();
    $('#fetch-4').hide();
    $('#fetch-5').hide();
    $('#fetch-6').hide();

    $('#fetch-1-error').show();
    $('#fetch-2-error').show();
    $('#fetch-3-error').show();
    $('#fetch-4-error').show();
    $('#fetch-5-error').show();
    $('#fetch-6-error').show();
}

var loadTimeout = setTimeout(tick, 1000);
var tack = 1000;

    $.ajax({
        url: '/game/configs/required/jquery-fetch/fetch-1.php?i=<?php echo $row["id"]; ?>',
        timeout: tack,
        cache: false,
        success: function(data) {
            $('#fetch-tpb-filesize').load('/game/configs/required/jquery-fetch/fetch-1.php?i=<?php echo $row["id"]; ?>');
            clearTimeout(loadTimeout);
        },
        error: function(data) {
            setInterval(function() {
                $('#fetch-1').show();
                $('#fetch-1').load('/game/configs/required/jquery-fetch/fetch-1.php?i=<?php echo $row["id"]; ?>');
                $('#fetch-1-error').hide();
            }, 1000);
        }
    });

As you can see in error I have tried to make it reload, but it doesn't stop after 1 second as the first time. Any one here who knows how to fix the problem?

Upvotes: 0

Views: 498

Answers (1)

epascarello
epascarello

Reputation: 207511

You are using setInterval inside the error function which will call that code block every second.

Also you are using a jQuery method that does all of the dirty work for you. If you want to use timeout: tack, you need to use $.ajax again. Why don't you just make it a function and call it again instead of copy and pasting code and code and code all over the place.

Upvotes: 2

Related Questions