0

Problem in JavaScript Animations Code

I have a doubt in this Code :-- function myMove() { var pos=0; var elem = document.getElementById("object"); var inter = setInterval(move, 10); function move() { if (pos == 1150){ pos=0; }else{ pos++; elem.style.left=pos+'px'; }}} i have doubt in "pos++" As i know ++ add 1 to number but in this code 1 is added continuously like in loop. Anyone Please explain this to me?

20th Jan 2018, 10:15 AM
Smile garg
Smile garg - avatar
4 ответов
+ 16
That's because you used an animation interval less that the default supported of your device... Use at least 60 for safety otherwise the loop will run many times before the animation refreshes... That's why we use requestAnimationFrame(move) instead of setInterval (also add a requestAnimationFrame(move) in bottom of move())
20th Jan 2018, 10:22 AM
Valen.H. ~
Valen.H. ~ - avatar
+ 14
function myMove() { var pos=0; var elem = document.getElementById("object"); requestAnimationFrame(move); function move() { if (pos == 1150){ pos=0; }else{ pos++; elem.style.left=pos+'px'; } requestAnimationFrame(move); } }
20th Jan 2018, 10:23 AM
Valen.H. ~
Valen.H. ~ - avatar
+ 2
What do you mean it's added continuously? There is no loop inside the move() function, but you do call the move() function every 10 milliseconds (so, 100 times every second). At this rate, you might indeed be under the impression that it acts like an infinite loop (since you never clear the interval). Do you want your animation to stop at some point?
20th Jan 2018, 10:26 AM
Thomas
0
Thanks Guys.. Got It!. BTW Thomas I know how to stop animation at a point. I was just asking how 1 is getting added to pos many times instead of just one time. But now i got how that was happening. Thanks For Help!
20th Jan 2018, 4:10 PM
Smile garg
Smile garg - avatar