JavaScript
Article

Delay AJAX call for X seconds

By Sam Deering

jQuery code snippet to delay AJAX call for X seconds. Could be used for events that require action before getting data from the server side via AJAX.

Update: There is an easier way to do this by using setTimeout() function – See below for an example.

Enjoy! :)

var pendingCall = { timeStamp: null, procID: null };

$('li a').click(function (e) {
    e.preventDefault();
    var getUrl = $(this).attr("href");
	var timeStamp = Date.now();

    var printCall = function () {
        $.ajax({
            url: getUrl,
            type: "GET",
            beforeSend: function () { },
            error: function (request) { alert(request) },
            success: function (data) {
                if (pendingCall.timeStamp != timeStamp) { return false; }
                $('#contentdiv').html(data);
                pendingCall.procID = null;
            }
        });
    };

    if (pendingCall.procID) {
        clearTimeout(pendingCall.procID)
    };
	//set the time before call 3000 = 3 seconds
    pendingCall = { timeStamp: timeStamp, procID: setTimeout(printCall, 3000) };
});

setTimeout Alternative

Here is a snippet that will remove loading mask from your page, one second after a website was loaded. You can setup a loading mask to cover your whole website while your website is loading preventing people form seeing loading images for example.
 

jQuery(document).ready(function () {
	setTimeout( "jQuery('#loading_mask').hide();", 1000 );
});

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • http://www.codesign2.co.uk Lewis Cowles

    just use setTimeout, it’s not hard to do, this tutorial is overkill to an easy situation

  • jquery4u

    Hi Lewis,

    Yes good point, this function was just an alternative to the setTimeout() function. I’ve updated the post so that people know this is also available.

    Cheers
    Sam

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.