如何制作一个真正的Javascript定时器

如何制作一个真正的Javascript定时器,javascript,animation,dom-events,Javascript,Animation,Dom Events,我正在寻找一种不使用库操作动画的方法 像往常一样,我在另一个setTimeout中设置一个setTimeout,以平滑用户界面 但是我想做一个更精确的函数来做,所以如果我想做一个50毫秒的每件 动画,我键入: ............ sum=0, copy=(new Date()).getMilliseconds() function change(){ var curTime=(new Date()).getMillisec

我正在寻找一种不使用库操作动画的方法
像往常一样,我在另一个
setTimeout
中设置一个
setTimeout
,以平滑用户界面
但是我想做一个更精确的函数来做,所以如果我想做一个50毫秒的每件 动画,我键入:

............
       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)
。。。。。。。。。。。。
总和=0,
copy=(新日期()).getmillizes()
函数更改(){
var curTime=(新日期()).getmillizes(),
diff=(1000+(curTime copy))%1000//计算每次设置超时之间的时间
日志(“不同时间的垃圾邮件:,不同)
和=差
复制=缩短时间
var cur=parseInt(p.style.width)

如果(sum对我来说太复杂,请使用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
}

那么。你有什么问题?另外,对于一个重要的问题,请提供一个人们可以复制/粘贴的示例,而不是一个随机的缩进严重的代码块。对不起,我现在要去JSFIDLE,等一下,你能评论一下你的代码,让我们知道你的核心思想是什么吗?否则,据我所知,你的核心思想是好的。代码没有问题吗是的。我已经做了一些评论,谢谢你回答我的问题。值得注意的是,
Date.now()
是ES5的一项功能。为了获得更广泛的支持,最好使用
new Date()
,在这种情况下可以互换。因为它们应该是数字,
+new Date()
,然后。在字符串连接以外的操作中使用日期对象会强制它进行编号,因此
var start=new date();var diff=new date()-开始
就足够了。为了内心的平静,我强迫自己去数字如果我知道一件事必须是一个数字,1+也不会杀死我的表现,而且代码更能揭示意图。我觉得依赖类型强制的所有细节是不对的,我唯一依赖的是“如果有一个字符串,所有的东西都是字符串”。那么你可以考虑<代码>编号(new DATE())<代码>或<代码> new DATE()。