Mrye Mrye - 1 month ago 9
Javascript Question

Jquery : Set delay for each iteration

Suppose this is the logic that I want :

// On fail return status = 500, else success will return PDF bytestream
function request() {
return $.ajax({
url: url,
async:false,
// other properties
});
}

$('#action').click(function(e) {

$("#loading").fadeIn("slow"); // display loading

while(true) {
if(request().status != 200) {
delay(3000);
} else { break; }
}

$("#loading").fadeOut("slow"); // hide loading
});


For testing delay without iteration and request, this code works well :

$(document).ready(function(){
$('#action').click(function(e) {
$("#loading").fadeIn("slow");
setTimeout(function() {
$("#loading").fadeOut("slow");
}, 5000);
e.preventDefault();
});
});


Problem started when I put some loops and request inside, like this :

var isOk;
$(document).ready(function(){
$('#action').click(function(e) {

$("#loading").fadeIn("slow");

while(true) {
request().always(function(jqXHR){
console.log(jqXHR);
if(jqXHR.status == 500) {
isOk = false;
setTimeout(function(){console.log("False")}, 3000);
} else { isOk = true; }
});

if(isOk) {break};
}

$("#loading").fadeOut("slow");
e.preventDefault();
});
});


It's like there's no delay in between iteration. The loading symbols fadeIn and fadeOut instantly. Any idea how to do the correct delay for iteration ?

Gab Gab
Answer

You should call .fadeOut() when ajax request is resolved, like this:

$(document).ready(function(){

    $('#action').click(function(e) { 
        e.preventDefault(); 

        $("#loading").fadeIn("slow");

        performRequest();

    });

    function performRequest() {

            request()
                .always(function(jqXHR){
                    console.log(jqXHR);

                    if(jqXHR.status === 500) {
                       console.log("False");
                       var t = setTimeout(function() { 
                           performRequest();    // retry after 3sec.
                           clearTimeout(t);
                       }, 3000);
                    } else { 
                       onRequestSuccess(); // success
                    }
            });
    }

    function onRequestSuccess() {
         $("#loading").fadeOut("slow");
    }

});