Neil Fender
Neil Fender

Reputation: 75

Ajax settimout when checking if file exists

I`m checking if a file exists. Using 1 second intervall to check. What I wanna achive: Firing an alert if after 10 seconds the file isnt found. I tried to settimeout inside the intervall, but with no success. Any Tipps would be great, thanks in advance.

var isLoading=new Boolean();
isLoading=false;
setInterval(
function(){                      
    $.ajax({
        url: ajaxRequestUrl,
        type: "GET",
        cache: false,                                  
        statusCode: {
            // HTTP-Code "Page not found"
            404: function() {
                if (isLoading===false){
                    do_this();
                }
            },
            // HTTP-Code "Success"
            200: function() {
                if (isLoading===true){
                    do_that();
                }

            }    
        }
    });     
},
1000);

Upvotes: 0

Views: 197

Answers (2)

erikscandola
erikscandola

Reputation: 2936

What you need is a variable to check after a second.

var isLoading=new Boolean();
isLoading=false;
var tick = 0;
var getFile = setInterval(function(){
    if(tick == 0) {
        $.ajax({
            url: ajaxRequestUrl,
            type: "GET",
            cache: false,                                  
            statusCode: {
                // HTTP-Code "Page not found"
                404: function() {
                    if (isLoading===false){
                        do_this();
                    }
                },
                // HTTP-Code "Success"
                200: function() {
                    if (isLoading===true){
                        do_that();
                    }
                }    
            }
        });
    }
    else if(tick == 10) {
        clearInterval(getFile);
        alert("File not found");
        tick = 0;
    }
    else {
        tick++;
    }
}, 1000);

In the interval I check if the tick is equals to 0 (not to make the same request several times), if yes I do the request otherwise wait. After 10 seconds show alert and then set tick to 0. In the example I also clear the interval not to continue to iterate. In this way you can then ask for a new file.

Upvotes: 0

rishikesh tadaka
rishikesh tadaka

Reputation: 483

I will suggest below code:

var isLoading=new Boolean();
isLoading=false;
var isFileFound=false;

$.ajax({
    url: ajaxRequestUrl,
    type: "GET",
    cache: false,                                  
    statusCode: {
        // HTTP-Code "Page not found"
        404: function() {
            if (isLoading===false){
                do_this();
            }
        },
        // HTTP-Code "Success"
        200: function() {
    isFileFound=true;
            if (isLoading===true){
                do_that();
            }

        }    
    }
});     

setTimeout(function(){
alert(isFileFound);
},10000);

Upvotes: 1

Related Questions