0
votes

I'm trying to create a function that will fade in appends to an element. To ensure the animations run sequentially and wait for the previous animation to finish, I'm trying to use a callback function (recursively) with fadeIn.

$(document).ready(function() {
    var messages = [];
    messages.push("First message");
    messages.push("Second message")

    function appendContentText(newText, callbackFunction, callbackArgument) {
        $("<div>" + newText + "</div>").hide().appendTo("#content").fadeIn(1000, callbackFunction(callbackArgument));
    }

    function runMessageSequence(introCounter = 0) {
        if (introCounter == messages.length) return;
        else appendContentText(messages[introCounter], runMessageSequence, introCounter + 1);
    }

    runMessageSequence();
});

The messages all fade in together though. So it seems to me like the subsequent fadeIn's are being called immediately rather than after the 1000 ms delay.

I suspect this might have something to do with the order I'm applying things like 'hide' and 'appendTo' and 'fadeIn' to the selector.

1

1 Answers

3
votes

My guess is that you are probably calling the function right away instead of referencing it. If you just edit as follows, it does what you want

$("<div>" + newText + "</div>").hide().appendTo("#content").fadeIn(1000, function(){
    callbackFunction(callbackArgument)
});

Check Fiddle