Javascript-Jquery - animate method inside for loop -
i have below loop, counts 1 100.
i want use animate method inside loop move picture smoothly, ie altering top , left attributes.
although can picture move, in 1 jerky animation. might bit dumb seems execute animations in 1 hit instead of gradually.
is javascript being asynchronous?
also there way can repeat in javascript,ie rather setting loop there way function can call @ end, so, example, can have display of animated divs bounce around etc. @ moment have set pre defined loop.
for (i=1; < 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"} ); };
this code should solve problem:
var = 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 can see example on jsfiddle.
the for
loop faster setinterval
if specific delay of 0. because setinterval
have min delay value of 4ms. question: why settimeout(function, 0) executed after next operation, not in moment of calling?
Comments
Post a Comment