I want use javascript setInterval function to achieve a box rotate animate effect, I want the animation keep 1.5 second, in 1.5s the box would rotate 360 degree, so I calculate the increment in one millisecond , and use setInterval function per millisecond.Here is my code:
var duration= 1500;//The animation duration time
var rotate = 360;//The rotate need to be rotate
var degPerSec = rotate / parseFloat(duration); //the increment per millisecond
var degree = 0;//the begin degree
console.time('rotate');
var timer = setInterval(function () {
degree = degree + degPerSec;
$('#test')[0].style.MozTransform = 'rotate(' + degree + 'deg)';
$('#test')[0].style.WebkitTransform = 'rotate(' + degree + 'deg)';
if (degree >= rotate) { //if reach 360 degree , clear the interval
clearInterval(timer);
console.timeEnd('rotate');// caculate the duration
}
}, 1)
})
The animation could execute successfully,but it seems it last not only 1.5s, when I use console.time to calculate the whole duration ,it last about 6s!Not 1.5s.Why this happened?How can I solve this problem?
Here is the demo
update::
Why I don’t use css3:cuz the rotate degree is as a parameter,which needed pass form outside, not defined already
Why on earth are you using Jquery for this when you could use a simple stylesheet? You’re already using Mozilla- & Webkit-specific branching code. Might as well just do it with CSS3 and be done with it. Much faster (uses native C code rather than JS) and much simpler.
EDIT: If you need to use a variable parameter for the degrees of rotation, this is still very do-able using JS: