Search code examples
javascriptjqueryjquery-callback

Set minimum wait time for AJAX callback action


I have an app built in HTML that loads fullscreen inside a modal with $.get()

I have a loading screen that is triggered when someone clicks the icon to load the app.

I want the loading screen to appear for a minimum of 2 seconds before clearing out and showing the app.

Is there a good, safe way to start a timer that runs for 2000 milliseconds, checks a variable that is populated by the callback to see if it is null, and then proceeds with a certain action only when the variable is loaded?

I know a while loop will do the trick, but might cycle 1000 times before the content loads on a slow day, and this seems like an inefficient way to do things.

Answer

$('#testApp').click(function() {
    var twoSecMin = $.Deferred();
    setTimeout(function () { twoSecMin.resolve(); }, 2000);
    $('#appModal').fadeIn(400);
    $.when($.get("/usm/portal/_layouts/monkeysphere/test.aspx"),twoSecMin).then(function (data) {
        $('#appContainer').html(data[0]);
        $('#appContainer').show();
        $('#appModal').fadeOut(200);
    });
});

Solution

  • If you're using a recent version of jQuery (1.5 or later), you can create a $.Deferred and resolve it with a fixed timeout:

    var twoSecMin = $.Deferred();
    setTimeout(function () { twoSecMin.resolve(); }, 2000);
    

    Also, save the jqXHR returned by $.get, which is an extended Deferred object:

    var ajaxReq = $.get("/usm/test.aspx", ...);
    

    Then wait for both:

    $.when(twoSecMin, ajaxReq).then(function (_, res) {
        // ready...
    
        var data = res[0];
        // ...
    });