Search code examples
jqueryarraysloopscycletiming

jquery iterating over an array containing another array to iterate over using a dynamically set delay


I have a JSON object that is basically an array of 'projects' and within each project there is a varying number of images.I want to be able to loop the outer (project) array, fading each one in then out. But after the fade in I want to be able to cycle through its relevant images (slideshow) before the outer array fades out and fades into the next project.

The problem I have is getting the the dynamically set delay timing to work correctly. The next project doesn't wait for the previous one to complete, and the very last one shows up way too late. It's obvious from looking at my code, that I am having a hard time understanding the whole timing aspect.

JSfiddle here.

<div class="delayDisplay"></div>

<div class="info">
    div 1
    <div class="img">1</div>
    <div class="img">2</div>
    <div class="img">3</div>
</div>

<div class="info">
    div 2
    <div class="img">1</div>
    <div class="img">2</div>
</div>

<div class="info">
    div 3
    <div class="img">1</div>
    <div class="img">2</div>
    <div class="img">3</div>
<div class="img">4</div>
</div>


$(document).ready(function() {

$('.info').each(function(index) {

    var info = $(this);  
    var img = info.children('.img');
    var transDur = 500;
    var imgDur = 2000;
    var galLegnth = img.length;
    var infoDelay = ((transDur * 2) + imgDur) * galLegnth + 200;

    setInterval(function() {

        info.fadeIn(transDur, function() {
            $('.delayDisplay').text(infoDelay);

            img.each(function(i) {  

                curImg = $(this);
                console.log(curImg.text());

                //curImg.delay(1200).show();

                setTimeout(function() {
                    curImg.fadeIn(500).delay(1000);
                }, 2000 * i);

            });

        }).delay(infoDelay).fadeOut(transDur);

    }, infoDelay * index);

});

});

Keep in mind and please don't comment asking why, but I am trying to avoid creating functions to do this right now. And yes the JSON data is being processed correctly. As you can see my only issue at this point is understanding the timing.


Solution

  • Instead of implementing delays, as @adeneo mentioned use callbacks on fadein Complete

    http://api.jquery.com/promise/#example-1

    the use of the promise function will allow you to do this easily and painlessly.