Search code examples
jqueryjquery-callback

Understanding stop() and callbacks in jQuery


I have this fiddle with a function like this:

$("#success").stop(true, true).css({
    "top": offT,
        "opacity": 0
}).animate({
    "top": "-=40",
        "opacity": 1
}, 700, function () {
    $(this).delay(4000).animate({
        "opacity": 0
    }, 1200);
});

When you click a button once, there's no problem. But try clicking a button and after roughly two seconds click another. You'll notice that rather than delaying the fade out for 4 seconds, the div hides much sooner. In other words, the callback initiated by the first click is still active when clicking on the second button. I find this strange, because I call stop(true,true). Doesn't this prevent the callback from the first click to be executed and finished? If not, how can I force it to do so?


Solution

  • It should prevent the callback to be executed, but after your second click the callback has already been executed - the delay is in queue.

    To prevent this you can use JS window.setTimeout() method and cancel the delay.

    See this answer: How to stop the delay.

    var delay;
    $("button").click(function () {
        var offT = $(this).offset().top;
        window.clearTimeout(delay);
        $("#success").stop(true, false).css({
            "top": offT,
                "opacity": 0
        }).animate({
            "top": "-=40",
                "opacity": 1
        }, 700, function () {
            delay = window.setTimeout(function() {
                $("#success").animate({
                    "opacity": 0
                }, 1200);
            }, 4000);
        });
    });