Crupuk
Crupuk

Reputation: 297

Jquery : delay fadeOut & clearQueue doesn't work?

I don't understand why this code doesn't work:

function Messages(type,text) {
    console.log("In function Message");
    $("#message").clearQueue();
    console.log("clearQueue :"+$("#message").queue("fx").length+" effet in queue");

    if($("#message").length > 0 && $("#message").not(":visible").length == 1) {
         $("#message").slideDown("slow");
    }

    $("#message").queue(function(){
         $(this).delay(5000).fadeOut("slow");
         $(this).dequeue();
    });
    console.log("Adding  "+$("#message").queue("fx").length+" effet in queue");
 } 

And this is the console log:

 In function Message
 1346clearQueue :0 effet in queue
 1356Adding  2 effet in queue

But it seems like clearQueue doesn't work because I have this:

Message appears, he disappears 5 second after..

Message appears, after 4 seconds, I call "Message" again, and #Message disappears after one seconds.

So, if Message is called more than one time, the delay doesn't change and #Message disappears allways 5 seconds after the first call..

Upvotes: 1

Views: 1700

Answers (1)

Nick Craver
Nick Craver

Reputation: 630469

.delay() is a setTimeout() wrapper, so clearing the queue simply has no effect on it at all (at least not yet, hoping this changes in a future jQuery release). When the delay is set, .dequeue() is called on the element when it finishes.

If you want to clear this you need to store the timeout yourself, something jQuery doesn't currently do internally. Doing it yourself looks like this:

function Messages(type,text) {
    var msg = $("#message");
    //clear old timer
    clearTimeout(msg.data("timer"));
    //clear previous queue
    msg.clearQueue();

    if(msg.filter(":hidden").length == 1) msg.slideDown("slow");

    //set and store a new timer
    msg.data("timer", setTimeout(function() { msg.fadeOut("slow"); }, 5000));
} 

Upvotes: 3

Related Questions