gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:52:09 25 4
gpt4 key购买 nike

我正在寻找一种不使用库来操纵动画的方法
和往常一样,我在另一个 setTimout 中创建了一个 setTimeout 以平滑 UI
但我想做一个更准确的函数来做,所以如果我想做一个 50ms-per-piece动画,然后我输入:

............
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 url:
http://jsfiddle.net/lanston/Vzdau/1/

最佳答案

对我来说太复杂了,使用 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
}

关于javascript - 如何制作一个真正的 Javascript 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8145408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com