这是我的情况,我需要加快功能运行时间,所以setInterval不是明智的选择吧?因为每次花费至少4毫秒。
那么,我可以将setInterval函数更改为requestAnimationFrame,但我不太了解requestAnimationFrame的工作原理。
例如
// some code here
var interval = setInterval(doSomething, 10)
var progress = 0
function doSomething(){
if (progress != 100){
// do some thing here
}else{
clearInterval(interval)
}
}
以及如何应用requestAnimationFrame?
答案 0 :(得分:0)
我认为理解requestAnimationFrame的关键在于保罗·爱尔兰的解释:
在一个rAF中排队的任何rAF将在下一帧执行。
来自requestAnimationFrame Scheduling For Nerds
var rafReference;
var progress = 0;
function doSomething(){
// only run 100 times
if (progress < 100){
/* do what you wanna do here */
progress++;
//recursively calls it self as requestAnimationFrame's callback
rafReference = requestAnimationFrame(doSomething) // passed as reference
}else{
cancelAnimationFrame(rafReference)
}
}
//starting the recursion
requestAnimationFrame(doSomething)
答案 1 :(得分:-1)
在小提琴中看起来更好 - &gt; just the code,no animation
为了简化,每个东西都在代码中注释。不需要使用setInterval。 当我们假设要清除间隔时,只需使用cancelAnimationFrame。
// This makes sure that there is a method to request a callback to update the graphics for next frame
var requestAnimationFrame =
window.requestAnimationFrame || // According to the standard
window.mozRequestAnimationFrame || // For mozilla
window.webkitRequestAnimationFrame || // For webkit
window.msRequestAnimationFrame || // For ie
function (f) { window.setTimeout(function () { f(Date.now()); }, 1000/60); }; // If everthing else fails
var cancelAnimationFrame =
window.cancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.msCancelAnimationFrame;
// your code here
var progress = 0;
function doSomething() {
if (progress != 100) {
// do something here
var myAnimation = requestAnimationFrame(doSomething);
} else {
// don't use clearInterval(interval) instead when you know that animation is completed use cancelAnimationFrame()
cancelAnimationFrame(myAnimation);
}
}
一些值得阅读的链接 - &gt;