1

I am analyzing some code from a book I am reading and there is a small piece that confuses me a little bit:

//... some code

setTimeout(function(){
   //...some code
   if(some condition)
      setTimeout(arguments.callee, 0);
}, 0);

What is a little confusing for me is that the same book mentions that the "callee" property has been deprecated and that it should not be used unless strictly necessary (I am paraphrasing). So I am wondering if this is one of those cases or if there could be a better way to accomplish the recursive call. Somewhere on the internet I read that the following may accomplish the same thing:

//... some code

setTimeout(function myRecursiveFunction(){
   //...some code
   if(some condition)
      setTimeout(myRecursiveFunction, 0);
}, 0);

Is this correct? Is there yet a better way to approach this? Is it safe and ok to keep using arguments.callee?

Thank you for any clarification.

Sergio Romero
  • 6,477
  • 11
  • 41
  • 71
  • possible duplicate of [Arguments.callee is deprecated - what should be used instead?](http://stackoverflow.com/questions/8361642/arguments-callee-is-deprecated-what-should-be-used-instead) – DavidRR Jun 18 '15 at 19:26

2 Answers2

1

arguments.callee is deprecated and may be removed.
It also makes the code harder for the browser to optimize.

Your second approach is correct.
When you create an anonymous function (function expression) with a name, that name becomes accessible to the code within the function expression.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

The second approach is best. What it actually does is it "hoists" the function declaration to the top of the nearest enclosing scope (the function in which this was defined), and names the function "myRecursiveFunction".

The alternative would be creating an anonymous scope like so:

setTimeout(
    (function(){
        var myRecursiveFunction = function() {
            console.log(myRecursiveFunction);
        };
        return myRecursiveFunction
    }),
    1000
)

or perhaps using a fixedpoint combinator from functional programming.

ninjagecko
  • 88,546
  • 24
  • 137
  • 145