-1

I have the below loop, which counts from 1 to 100.

I want to use the animate method inside this loop to move a picture smoothly, ie by altering its top and left attributes.

Although I can get the picture to move, it does it in one jerky animation. I might be a bit dumb but it seems to execute all the animations all in one hit instead of gradually.

Is this something to do with javascript being asynchronous?

Also is there a way I can get something to repeat in Javascript,ie rather than setting up a loop is there a way a function can call itself at the end, so, for example, I can have a display of animated divs which constantly bounce around etc. At the moment I have to set up a pre defined loop.

for (i=1; i < 100; i++) {
    var FirstTop = (FirstTop + FirstTopGoal);
    var FirstLeft= (FirstLeft+ (FirstLeftGoal));
    var SecondTop = (SecondTop+ (SecondTopGoal));
    var SecondLeft = (SecondLeft + (SecondLeftGoal));
    if (FirstTop<100){Firsttop=100;FirstTopGoal    = 2 - Math.random()*4;};
    if (FirstLeft<50){FirstLeft=50;FirstLeftGoal    = 2 - Math.random()*4;};
    if (FirstTop>130){Firsttop=130;FirstTopGoal    = 2 - Math.random()*4;};
    if (FirstLeft>500){Firsttop=500;FirstLeftGoal    = 2 - Math.random()*4;};
    $("#first").animate(
        {top: FirstTop,left:FirstLeft},
        {duration: 0,
        easing: "linear"}
    );
};
John
  • 45
  • 4
  • You've set the animation duration to be 0 so I don't know why you expect it to show smooth animation. – JJJ Jan 28 '16 at 13:44

1 Answers1

-1

This code should solve your problem:

var i = 1;
var interval = setInterval(function(){
    if(i < 100) {
        i++;

        var FirstTop = (FirstTop + FirstTopGoal);
        var FirstLeft= (FirstLeft+ (FirstLeftGoal));
        var SecondTop = (SecondTop+ (SecondTopGoal));
        var SecondLeft = (SecondLeft + (SecondLeftGoal));
        if (FirstTop<100){Firsttop=100;FirstTopGoal    = 2 - Math.random()*4;};
        if (FirstLeft<50){FirstLeft=50;FirstLeftGoal    = 2 - Math.random()*4;};
        if (FirstTop>130){Firsttop=130;FirstTopGoal    = 2 - Math.random()*4;};
        if (FirstLeft>500){Firsttop=500;FirstLeftGoal    = 2 - Math.random()*4;};

        $("#first").animate(
            { top: FirstTop, left:FirstLeft}, 
            {duration: 0, easing: "linear"}
        );
    }
    else if(i == 100){
        clearInterval(interval);
    }
}, 1);

Use setInterval instead of for loop because. Here you can see an example on jsFiddle.

The for loop is faster than setInterval also if you specific a delay of 0. This is because setInterval have a min delay value of 4ms. Look also this question: Why setTimeout(function, 0) is executed after next operation, but not in the moment of calling?

Community
  • 1
  • 1
erikscandola
  • 2,854
  • 2
  • 17
  • 24