Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    });
});
like image 759
Wesley Avatar asked Dec 13 '12 06:12

Wesley


2 Answers

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];
    // ...
});
like image 200
Jonathan Lonowski Avatar answered Oct 16 '22 02:10

Jonathan Lonowski


You could probably just use a setTimeout(fn, 2e3) to do this.

For testing if your variable is null, you could use yourVariable === null.

like image 37
alex Avatar answered Oct 16 '22 01:10

alex