Anyway, to detect a recursive method in javascript / jQuery?

I am working on a small part of the calculation code. I need to identify whenever recursion happens in javascript / jQuery, and I need to stop this recursion.

Is there any api to support this in javascript / jQuery?

+3
source share
3 answers

You can implement your own recursive protection. There is nothing in jQuery that could help prevent recursion.

function myFunc(arg) {
    // if this function already executing and this is recursive call
    // then just return (don't allow recursive call)
    if (myFunc.in) {
        return;
    }

    // set flag that we're in this function
    myFunc.in = true;

    // put your function code here


    // clear flag that we're in this function
    myFunc.in = false;

}

myFunc.in = false;

You can also turn a boolean into a counter and allow recursion only up to a certain number of levels.

FYI, JS , , , - , . , , .


, , :

 var myFunc = (function() {
     var inCntr = 0;
     return function(args) {
         // protect against recursion
         if (inCntr !== 0) {
             return;
         }
         ++inCntr;

         try {

             // put your function code here

         } finally {
             --inCntr;
         }

     }
 })();

: try/finally, , ( ).

+5

caller ( ):

function Test()
{
    if (Test.caller === Test && confirm("Recursion detected, stop?"))
        return;
    Test();
}

Test();

, caller , .

+2

Another tricky trick. Will not work if you use something like .bind(this)for recursion.

boom();

function boom () {
  if(arguments.callee === arguments.callee.caller) {
    console.log('no recursion will happen');
    return;
  }
  boom();
}
Run code

A simple solution could be a flag in the parameter

boom2();

function boom2 (calledRecursively) {
  if(calledRecursively) {
    console.log('no recursion will happen');
    return;
  }
  boom2(true);
}
Run code
0
source

All Articles