如何制作一个真正的javascript计时器

时间:2011-11-16 01:12:00

标签: javascript animation javascript-events

我正在寻找一种不使用图书来操纵动画的方法 像往常一样,我在另一个setTimout中创建一个setTimeout,以平滑UI 但我想做一个更准确的功能,所以如果我想制作一个50ms的每件 动画,我输入:

............
           sum=0,
           copy=(new Date()).getMilliseconds()

       function change(){


        var curTime=(new Date()).getMilliseconds(),
            diff=(1000+(curTime-copy))%1000  //caculate the time between each setTimeout

        console.log("diff time spam: ",diff) 

        sum+=diff
        copy=curTime

        var cur=parseInt(p.style.width)

        if (sum<47){//ignore small error
        //if time sum is less than 47,since we want a 50ms-per animation  

                    // we wait to count the sum to more than the number
            console.log("still wating: ",sum)
        }
        else{   
                    //here the sum is bigger what we want,so make the UI change
            console.log("------------runing: ",sum)
                sum=0 //reset the sum to caculate the next diff
                if(cur < 100)
                {

                    p.style.width=++cur+"px"

                }
                else{

                    clearInterval(temp)

                }
            }

       }

       var temp=setInterval(change,10)

我不知道我的代码的核心思想是对的,任何人都可以获得一些关于如何在大多数浏览器中制作更准确的计时器的想法?谢谢:-)
设置JsFiddle网址:
http://jsfiddle.net/lanston/Vzdau/1/

1 个答案:

答案 0 :(得分:3)

对我来说看起来太复杂了,请使用setInterval和一个开始日期,例如:

var start = +new Date();
var frame = -1;
var timer = setInterval(checkIfNewFrame, 20);

function checkIfNewFrame () {
  var diff = +new Date() - start;
  var f = Math.floor(diff / 50);
  if (f > frame) {
    // use one of these, depending on whether skip or animate lost frames
    ++frame; // in case you do not skip
    frame = f; // in case you do skip
    moveAnimation();
  }
}

function moveAnimation () {
  ... do whatever you want, there is new frame, clear timer past last one
}