views:

47

answers:

1

Hello,

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 dosn"t change and #Message disapears allways 5 seconds after the first call..

Could you help me ?

(Sorry for basic english, i'm trying to do the best as i can )

A: 

.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));
} 
Nick Craver
Thanks it works !!(Another new thing learned)
Crupuk
@Crupuk - welcome :)
Nick Craver