Please explain this requestAnimationFrame idiom

There are many places (e.g. How to use requestAnimationFrame? ) that can be fixed window.requestAnimationFrameas shown below. I do not understand why the right side of the job is tied to a function call.


window.requestAnimFrame = (function(){
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
})();
+3
source share
3 answers

I already wondered the same thing. I'm pretty sure that Google really loves closure. Of course, there is not a single variable, this is a "safe" thing.

As far as I can tell, this is the same, without any changes to interference with namespaces (a common reason to use a similar closure):

window.requestAnimFrame = 
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
0
source

In the OP example, putting the code in a closure does nothing (at least what I know :-)

http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating , . , .

, :

  • ,
  • .

JavaScript - .

, nobi

0

requestAnimationFrametakes one argument: function to run. However, it setTimeoutperforms the function to start, as well as the delay after which it starts. Therefore, although you can simply assign individual functions directly, you need to create a closure for setTimeoutso that you can assign a second argument.

This is basically a form of currying .

-2
source

All Articles