Frage

I've an jQuery code that simply makes some ajax request.

Most of time it takes less than second to get the respond, so I can show the results to the user.

But sometimes (about 5% of reloads) it takes few seconds (and I'm ok with that, the server is a bit busy).

I would like to show "Please wait" text when it takes more then 2 seconds. But not when it takes less then 2 seconds (so user won't get confused by rapid show/hide of message).

How to make it in the most efficient and simplest way?

The current jQuery code:

jQuery.ajax({
    url: "loadData.php",
    dataType: 'json',
    type: 'GET',
    success: function(result){
        showResultsToUser(result);
    }
});
War es hilfreich?

Lösung

Something like this:

var cancelMe = setTimeout(function() {
   $('#loading').show(); // assuming your loading element has the id "loading"
}, 2000); // show loading element in 2 seconds

jQuery.ajax({
    url: "loadData.php",
    dataType: 'json',
    type: 'GET',
    success: function(result){
        showResultsToUser(result);
        clearTimeout(cancelMe); // don't run if it hasn't run yet
        $('#loading').hide(); // hide the loading element if it's shown
    }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top