这是我的情况,我需要加快函数运行时间,所以 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?
最佳答案
我认为理解requestAnimationFrame的关键在于paul Irish的解释:
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)
关于setinterval - 如何用 requestAnimationFrame 替换 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17707508/