TheBlackBenzKid
TheBlackBenzKid

Reputation: 27087

Jquery Delay slideDown using time();

Sorry I could not find this.

$('div#loader').slideDown("fast").delay(1.5);

Does not word as expected, I want it to slideDown, then stay in that mode for 1.5 seconds and then the load function which happens very fast and then it slides up using fast. I thought delay(); was the correct approach.

Full function for those who wish to see:

$(document).ready(function () {
    function last_msg_funtion() {
        var ID = $(".pic_box:last").attr("id");
        $('div#loader').slideDown("fast").delay(1.5);
        $.post("/?action=get&id=" + ID,
        function (data) {
            if (data!="") {
                $(".pic_box:last").after(data);
            }
            $('div#loader').slideUp("fast");
        });
    };
});

Upvotes: 0

Views: 2085

Answers (2)

Andrew
Andrew

Reputation: 13853

Delay only delays functions that come after it in the chian, so it is delaying nothing there. You are better off using setTimeout here IMO

$('div#loader').slideDown("fast", function(){
   setTimeout(function(){
    $.post("/?action=get&id=" + ID,
    function (data) {
        if (data!="") {
            $(".pic_box:last").after(data);
        }
        $('div#loader').slideUp("fast");
    });
}, 1500);
});

Here is the delay code if you are interested,

// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
    time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
    type = type || "fx";

    return this.queue( type, function( next, hooks ) {
        var timeout = setTimeout( next, time );
        hooks.stop = function() {
            clearTimeout( timeout );
        };
    });
},

You can see how it only takes whatever is next in the function chain and delays that.

Upvotes: 2

Marcelo Diniz
Marcelo Diniz

Reputation: 2499

You could define a wait helper function and run your code after waiting for 1.5 secs:

$.wait = function(time) {
  return $.Deferred(function(dfd) {
    setTimeout(dfd.resolve, time);
  });
}


$(document).ready(function () {
    function last_msg_funtion() {
        var ID = $(".pic_box:last").attr("id");
        $('div#loader').slideDown("fast");
        $.wait(1500).then(function() {
            $.post("/?action=get&id=" + ID, function (data) {
                if (data != "") {
                    $(".pic_box:last").after(data);
                }
                $('div#loader').slideUp("fast");
            });
        });
    };
});

The wait function makes your code reads better IMO

Upvotes: 1

Related Questions