Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: function call to itself

I suppose the following code:

jQuery("#mybutton").click(function(){

    //do something

});

How could I recall to this function "anonymous"?, I can not put a name to this function:

var xfun = function(){

    //do something

}

jQuery("#mybutton").click(xfun);

I can do something like this:

var working = false;
jQuery("#mybutton").click(function(){

  if (working){
    var _this = this;
    _this._eventType = e.type;
    setTimeout(function() { jQuery(_this).trigger(_this._eventType); }, 200);
    return false;
  }
  //do something

});

what I need is something like this:

var working = false;
jQuery("#mybutton").click(function(){

  if (working){
    setTimeout( this_function, 200);
    return false;
  }
  //do something

});

thanks.

EDIT:

Solution:

jQuery("#mybutton").click(function(){
  if (working){
    var fn = arguments.callee;
    var _this = this;
    setTimeout(function(){fn.call(_this);}, 200);
    return false;
  }
  //do something    
});
like image 376
andres descalzo Avatar asked Nov 24 '09 17:11

andres descalzo


People also ask

How do you call a function within itself in JavaScript?

Recursion is a process of calling itself. A function that calls itself is called a recursive function. The syntax for recursive function is: function recurse() { // function code recurse(); // function code } recurse();

How do you call a function by itself?

Calling a function inside of itself is called recursion.

Which function repeatedly calls itself?

Recursion is a technique used to solve computer problems by creating a function that calls itself until your program achieves the desired result.

What is a recursive function in JavaScript?

Recursive function calls itself until condition metIt keeps going until the number is equal to 0, in which case it stops.


2 Answers

You can indeed name your anonymous function:

jQuery("#mybutton").click(function doWork(){
  if (working){
    setTimeout(doWork, 200);
    return false;
  }
  //do something    
});

You can also use arguments.callee:

jQuery("#mybutton").click(function(){
  if (working){
    setTimeout(arguments.callee, 200);
    return false;
  }
  //do something    
});

I'd go with the former.

like image 187
Crescent Fresh Avatar answered Oct 11 '22 12:10

Crescent Fresh


Can you explain why you can't name the function? You can use arguments.callee to get a reference to the current function, but that is deprecated and I'm not sure how much support it has among current browsers.

like image 23
jthg Avatar answered Oct 11 '22 13:10

jthg