我正在处理计算代码的一小部分。我需要识别javascript/jQuery中的递归,并终止该递归。
是否有任何API可以支持这个功能在javascript/jQuery中?
我正在处理计算代码的一小部分。我需要识别javascript/jQuery中的递归,并终止该递归。
是否有任何API可以支持这个功能在javascript/jQuery中?
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's code here
// clear flag that we're in this function
myFunc.in = false;
}
myFunc.in = false;
var myFunc = (function() {
var inCntr = 0;
return function(args) {
// protect against recursion
if (inCntr !== 0) {
return;
}
++inCntr;
try {
// put your function's code here
} finally {
--inCntr;
}
}
})();
另一种靠不住的技巧。如果你在递归中使用类似.bind(this)
或者使用箭头函数,它将无法工作。
boom();
function boom () {
if(arguments.callee === arguments.callee.caller) {
console.log('no recursion will happen');
return;
}
boom();
}
boom2();
function boom2 (calledRecursively) {
if(calledRecursively) {
console.log('no recursion will happen');
return;
}
boom2(true);
}