如何用 requestAnimationFrame 替换 setInterval [英] how to replace setInterval by requestAnimationFrame
问题描述
这是我的情况,我需要加快函数的运行时间,所以 setInterval 不是一个明智的选择,对吧?因为每次至少要花费4ms.
Here is my situation, I need to speed up the function running time, so setInterval is not a wise choose, right? Since it will cost at least 4ms for each time.
所以,我可以将 setInterval 函数更改为 requestAnimationFrame,但我不太明白 requestAnimationFrame 的工作原理.
So, may I change setInterval function to requestAnimationFrame, but I don't quite understand how the requestAnimationFrame works.
例如
// some code here
var interval = setInterval(doSomething, 10)
var progress = 0
function doSomething(){
if (progress != 100){
// do some thing here
}else{
clearInterval(interval)
}
}
以及如何应用 requestAnimationFrame?
and how can I apply requestAnimationFrame?
推荐答案
我认为理解requestAnimationFrame的关键在于paul Irish的解释:
I think the key to understand requestAnimationFrame lies in paul Irish's explanation:
任何在 rAF 中排队的 rAF 将在下一帧中执行
Any rAFs queued in a rAF will be executed in the next frame
来自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)
这篇关于如何用 requestAnimationFrame 替换 setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!