user1379533
user1379533

Reputation:

Beginner JavaScript - restarting my for loop

I have an animation running in 4 steps, when the 4 steps are over, I would like it to restart.

var aSteps = [
    {
        "x": "800",
        "y": "0"
    },
    {
        "x": "800",
        "y": "500"
    },
    {
        "x": "0",
        "y": "500"
    }, {
        "x": "0",
        "y": "0"
    }
];

var iStepsLength = aSteps.length;
for (var i = 0; i < iStepsLength; i++) 
{
    $('#P1').animate
    ({
        left: aSteps[i].x,
        top: aSteps[i].y,
     }, 1000);
}

I've tried to add an if statement like.

if (i == 3)
{
    i=0;    
}

But then my browser will just crash because it runs the for loop infinitely. I hope that you can help me out, and teach me what it is that I'm doing wrong.

Upvotes: 2

Views: 85

Answers (2)

macsplean
macsplean

Reputation: 609

set the for loop equal to a function. call the function, then call it again. EDIT: Like this:

function forloop() { 
   for (var i = 0; i < iStepsLength; i++) {
     $('#P1').animate ({ left: aSteps[i].x, top: aSteps[i].y, }, 1000); 
   }
}

then you can just call the function whenever you want the loop to run like so:

forloop()

Upvotes: -1

gurvinder372
gurvinder372

Reputation: 68393

.animate() can take a callback which will be invoked when the animation has ended:

function animateSteps( counter ) {
    $('#P1').animate({
        left: aSteps[ counter ].x,
        top: aSteps[ counter ].y,
     }, 1000, function(){
         if (counter == 3)
         {
            counter=0;    
         }
         animateSteps( counter + 1 );
     });
}

animateSteps( 0 );

Upvotes: 2

Related Questions