Using Jquery deferreds and 'for' loop to render dynamic data using Jquery effects in sequential order

465 views Asked by At

I want to use a 'for' loop (not reduce method or forEach or any other method) to iterate through an array of dynamic data (number of values can vary) and use Jquery deferreds in order to display each value using Jquery effects in sequential order (effect must finish before next array item is displayed)

Here is a block of code that works when using static code without 'for' loop -- as you can see 1 value is faded in at a time:

<div id="container"></div>

<script>
//I want to be able to process data in an array like this -- but currently this array is not being used below
testdata = [1,2,3,4];


var fadeIn1 = function(){
    console.log("started fade in 1");
    var promise = $("<h1>test 1</h1>").hide().appendTo("#container").fadeIn(2000);
    return promise.promise();
};

var fadeIn2 = function(){
    console.log("started fade in 2");
    var promise = $("<h1>test 2</h1>").hide().appendTo("#container").fadeIn(2000);
    return promise.promise();
};

var fadeIn3 = function(){
    console.log("started fade in 3");
    var promise = $("<h1>test 3</h1>").hide().appendTo("#container").fadeIn(2000);
    return promise.promise();
};

var kickoff = $.Deferred();

firstFadeIn = kickoff.then(function(){
    console.log("kickoff");
    return fadeIn1();
});

secondFadeIn = firstFadeIn.then(function(){
    console.log("second fadein");
    return fadeIn2();
});

thirdFadeIn = secondFadeIn.then(function(){
    console.log("third fadein");
    return fadeIn3();
});

kickoff.resolve();
</script>

I want to integrate the code above to work within a 'for' loop and be flexible to be able to process any number of array items.

1

There are 1 answers

3
Taplar On

Maybe something like this, if I understand what you are after.

var testdata = [1,2,3,4];
var promise;

function fadeIn(fadeNumber) {
    return $("<h1>test "+ fadeNumber +"</h1>").hide().appendTo("#container").fadeIn(2000).promise();
}

testdata.reduce(function(promise, fadeNumber){
  return promise ? promise.then(fadeIn.bind(null, fadeNumber)) : fadeIn(fadeNumber);
}, null);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>