3

there are a lot of places (e.g. How to use requestAnimationFrame?) that fix window.requestAnimationFrame as below. I do not understand why the right hand side of the assignment is wrapped in 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);
    };
})();

Community
  • 1
  • 1
akonsu
  • 28,824
  • 33
  • 119
  • 194

3 Answers3

0

I've wondered the same thing before. I'm pretty sure Google just really likes closures. Granted there is not one variable in there, it's a 'safe' thing to do.

As far as I can tell, this is the exact same thing, without any change of interfering with namespaces (a general reason to use a closure like that):

window.requestAnimFrame = 
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
Colin Godsey
  • 1,293
  • 9
  • 14
  • it just occurred to me. whoever wrote this in the first place was using some sort of translator such as coffeescript, that resulted in this statement. – akonsu Apr 19 '12 at 22:20
0

In the OP example, putting the code into the closure does nothing (at least what I am aware of :-)

Look here http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating for a similar function doing the same thing with a local variable. In this case, the variable would end up globally if it weren't inside the closure.

So there are two things involved:

  • a function to embed variables so they don't become global
  • executing this function immediately to run the code.

Here Immediate functions JavaScript is another discussion about these immediate functions.

All the best, nobi

Community
  • 1
  • 1
virtualnobi
  • 1,140
  • 2
  • 11
  • 35
-2

requestAnimationFrame takes one argument: the function to run. However setTimeout takes the function to run as well as a delay after which to run it. So while you can just assign the individual functions directly, you have to create a closure for setTimeout so that you can assign the second argument.

It's basically a form of currying.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • this would be true, except the setTimeout is wrapped in it's own function already. All possible returns can handle the same argument structure. – Colin Godsey Apr 19 '12 at 22:11
  • I am referring to the outer function. The one that takes no arguments. Yes the inner one that wraps setInterval is used to curry setInterval. – akonsu Apr 19 '12 at 22:12