Caio Kawasaki
Caio Kawasaki

Reputation: 2950

Run callback function in the middle of an animation instead of the end

Okay, I have the code below to put opacity div after div, after the function runs it takes 500 milliseconds to run again and I need it to run the function 100 milliseconds or less during the previous animation.

Here is my jquery code:

var children = [];
        $("#prod-general").children().each(function() {
            children.push(this);
        });

        function fadeThemOut(children) {
            if (children.length > 0) {
                var currentChild = children.shift();
                $(currentChild).set.animate({
                    'opacity': '1'},
                    500, function() {
                        fadeThemOut(children);
                });
            }
        }

Here is a fiddle: http://jsfiddle.net/r5bqatpz/2/

Upvotes: 2

Views: 288

Answers (2)

Shubh
Shubh

Reputation: 6741

Proper solution; Replace your method with this :-

function fadeThemOut(children) {
    if (children.length > 0) {
        var currentChild = children.shift();
        $(currentChild).animate({
                'opacity': '1'
            },
            500);
        var myVar = setInterval(function() {
            fadeThemOut(children);
        }, 100);

    }
}

Upvotes: 1

Jan Hommes
Jan Hommes

Reputation: 5152

Use a timeout:

    var children = [];
    $("#prod-general").children().each(function() {
        children.push(this);
    });

    function fadeThemOut(children) {
        if (children.length > 0) {
            var currentChild = children.shift();
            $(currentChild).set.animate({
                'opacity': '1'},
                500, function() {
                    //fadeThemOut(children);
            });
            setTimeout(function() {
                 fadeThemOut(children);
            },100);
        }
    }

here is a fiddle: http://jsfiddle.net/r5bqatpz/3/

Upvotes: 2

Related Questions