Search code examples
jqueryloaddelay

jQuery — Using .delay() to postpone a .load()?


I've just run into an issue with using jQuery's .delay() method (v 1.4.2) to try to delay a following .load() method.

Like so:

$('myElement').delay(500).load('myPage.php');

It seems to just ignore the .delay().

I've evenutally figured out a work-around like so:

setTimeout(function(){
    $('myElement').load('myPage.php');
}, 500);

But, that's not as elegant. Anyone else run into this and found a better solution?

Thanks.


Solution

  • Yes, the the delay()(docs) method will be ignored, because the load()(docs) method is not automatically queued.

    The setTimeout is probably your best option, though you could technically accomplish it with .delay() if you add the load() call to the queue using the queue()(docs) method.

    $('myElement').delay(500).queue(function( nxt ) {
        $(this).load('myPage.php');
        nxt();
    });
    

    The function is added to the queue. You need to then call the parameter of the function to free up the queue. There's a method called the dequeue()(docs) method that can accomplish this as well.