how to replace setInterval by requestAnimationFram

2019-07-03 16:27发布

问题:

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.

So, may I change setInterval function to requestAnimationFrame, but I don't quite understand how the requestAnimationFrame works.

For example

// some code here
var interval = setInterval(doSomething, 10)
var progress = 0
function doSomething(){
    if (progress != 100){
        // do some thing here
    }else{
        clearInterval(interval)
    }
}

and how can I apply requestAnimationFrame?

回答1:

Looks better in a fiddle-->just the code,no animation

Every thing is commented inside the code for simplification.No need of using setInterval. Just use cancelAnimationFrame when we are suppose to clear interval.

 // 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);
    }        
}

Some Links worth a read-->

  1. CreativeJs---the best explanation any one could give,Every begineer must read
  2. CancelAnimationFrame
  3. link 3-->in context of your question
  4. I found this fiddle on google,quite the same that you want.

Other things that you should know:

  • RAF is still in the development stage.
  • Why doesn't jQuery use requestAnimationFrame?