Pya*_*are 3 javascript recursion jquery
我正在研究计算代码的一小部分.我需要确定每当javascript/jQuery中出现递归时我需要终止递归.
在javascript/jQuery中有没有支持这个的api?
您可以实现自己的递归保护.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;
Run Code Online (Sandbox Code Playgroud)
您还可以将布尔值转换为计数器,并允许递归仅达到一定数量的级别.
仅供参考,因为JS是单线程的,如果您的函数从不属于您的代码中获取某种回调,这应该只是一个可能需要保护的问题.如果它是你自己的所有代码,那么你应该确保自己的代码不会导致这类问题.
这是一个更加简单的版本,可以在闭包中保护计数器,因此无法在函数外部进行操作:
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;
}
}
})();
Run Code Online (Sandbox Code Playgroud)
注意:这使用try/finally块,因此即使您的代码或您调用的任何代码抛出异常,计数器仍然被清除(因此它永远不会被卡住).
| 归档时间: |
|
| 查看次数: |
1644 次 |
| 最近记录: |