Reputation: 97
When I try to move a DIV using jquery with the help of setTimeout, it just works fine and is moving seamlessly like this:
setTimeout("moveObject()", 10);
function moveObject() {
$('.object').css("left", parseInt($('#object').css("left")) + 1);
}
It's moving like it's moving in Flash, you know seamlessly.. But there are some issues with setTimeout which has 10 ms, when the browser tab is in blur, timeout stops and doesn't make the job it has to.
Therefore, I thought it would be a good idea to use animate of JQuery to deal with this. I have changed the code to this:
$("#object").animate({left: parseInt($('#object').css("left")) + 100}, 1000, "linear", function() {} );
In the first code, object is moving 1px in 10ms. In the second code, object is moving 100px in 1000ms. So I think these two codes should do the same but they don't.
First code is moving object seamlessly, but the second is not that seamlessly. There are some corruptions in the movement.
My question is: How can I move this object (without using timeout) seamlessly? and It would be great if I can set a speed to that. Note: I'm not using HTML5 so I'm looking for a solution which works with jquery & HTML
Upvotes: 3
Views: 315
Reputation: 97
The solution for this question is this:requestAnimationFrame https://gist.github.com/mrdoob/838785
Upvotes: 0
Reputation: 76
As mentioned by adeneo you should take a look at CSS3 animations. Here is a really good article on MDN about transition property. Please also take a look at css transforms which should be useful in your case.
To smoothly move an element you only need to dynamically add below class to it.
.move-right {
transform: translate3d(100px, 0px, 0px);
transition: all 1s linear;
}
I've put together a small example which you might use as a starting point: https://jsfiddle.net/5bo5c8st/3/
Upvotes: 2
Reputation: 318342
jQuery uses timeouts internally to animate, there's no other way to do this.
Generally you get better flow if you use the timers in Window.requestAnimationFrame
instead of window.setTimeout
, as it's built for animating and has higher precision..
What you really should be doing is looking at libraries like GSAP from Greensock, or consider using CSS3 for the animation, which would give you a much smoother animation most of the time.
Also note that you're really calling eval
on the function as you're passing in a string to setTimeout that is evaluated, you should just reference the function
setTimeout(moveObject, 10);
and 10 milliseconds is a really low number, that used to be the absolute minimum, these days HTML5 sets it to 4ms, but not all browser follow that, only a few years back most browsers couldn't go below 50ms.
Upvotes: 2