对使用javascript setInterval进行动画处理感到困惑 [英] Confuse about using javascript setInterval to do animate job

查看:144
本文介绍了对使用javascript setInterval进行动画处理感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用setInterval在javascript中实现动画效果,我希望在1000msdiv的宽度增加200px(盒子的原点宽度是100px):

I try to use setInterval to achieve animate effect in javascript, I want a div's width increase 200px(the box's origin width is 100px) in 1000ms:

var MAX = 300, duration = 1000;
var inc = parseFloat( MAX / duration );

var div = $('div')[0];
var width = parseInt(div.style.width, 10);

function animate (id) {
    width += inc;
    if (width >= MAX) {
        clearInterval(id);
        console.timeEnd("animate");
    }
    div.style.width = width + "px";
}

console.time("animate");
var timer = setInterval(function () {
    animate(timer);
}, 0)

,而我使用console.time来计算所需的时间,但是,它总是要花3秒以上的时间,而不是1秒.

and I use the console.time to calculate how much time it take, however, it always take 3 second and more, not 1 second.

那我的代码怎么了?

演示在这里

但是当我使用jquery动画时,它与我指出的时间相同:

but when I use jquery animate, it just as the same time as I pointed:

console.time("animate");
$('div').animate({
    width: '300px'
}, { 
    duration: 1000,
    complete: function () {
        console.timeEnd("animate");
    }
})

这是演示

那为什么jquery可以做到呢?秘诀是什么?

So why jquery could achieve it?What's the secret?

推荐答案

秘密"是计算每帧需要采取的步骤.

The "secret" is to calculate the steps you need to take per frame.

这是一个更新的示例(进行了一些优化):
http://jsfiddle.net/AbdiasSoftware/nVgTj/7/

Here is an updated example (with some optimizations):
http://jsfiddle.net/AbdiasSoftware/nVgTj/7/

//init some values
var div = $('div')[0].style;
var height = parseInt(div.height, 10);
var seconds = 1;

//calc distance we need to move per frame over a time
var max = 300;
var steps = (max- height) / seconds / 16.7;

//16.7ms is approx one frame (1000/60)

//loop
function animate (id) {
    height += steps; //use calculated steps
    div.height = height + "px";

    if (height < max) {
        requestAnimationFrame(animate);
    }
}

animate();

请注意,正如hh54188指出的那样,requestAnimationFrame并非在所有浏览器中都可用(Chrome和Firefox支持带前缀的前缀).

Note that as hh54188 points out, requestAnimationFrame is not available in all browsers yet (Chrome and Firefox supports it with prefixes).

您可以使用此polyfill来使用呼叫,无论如何,但是如果requestAnimationFrame不可用,请优雅地回退到setTimeout.

You can use this polyfill which allow you to use the call no matter, but fall backs gracefully to setTimeout if requestAnimationFrame shouldn't be available.

http://www.paulirish.com/2011/requestanimationframe-for -smart-animating/

这篇关于对使用javascript setInterval进行动画处理感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆