首页 文章

递归动画抛出:超出最大调用堆栈大小

提问于
浏览
0

我们目前正在尝试将我们网页中使用的jquery从1.8升级到1.10.1,但这打破了页面中的一些功能 . 我能够隔离实际代码并且很惊讶地看到了这一点 . 我之前运行的递归动画代码抛出了错误 . 下面是代码 .

<script>
         $(document).ready(function(){
             glowOpenItems(500);
         });
         function glowOpenItems(duration){


                    $('#dialog').addClass('glowed',duration, function(){ 
                        $(this).removeClass('glowed',duration,function(){glowOpenItems(duration)});
                    });

            }
    </script>
    <style>
        .glowed{
                box-shadow: 0px 0px 40px 3px #e14f1c;
              }
    </style>
    <div id="dialog" title="Basic dialog">
      <p>Test Code</p>
    </div>

进一步调查发现这件事情有效

$(document).ready(function(){

            animate();
         });

         function animate() {
                $('#dialog').animate({backgroundColor:'#ffcc00'}, 500, function(){
                    $('#dialog').animate({backgroundColor:'#3b5998'}, 500, function(){
                            animate();
                    });
                });
            }

但每当我将animate方法改为 addClass 时,我都会"Uncaught RangeError: Maximum call stack size exceeded " . 似乎jquery的addclass中有变化 . 任何帮助将不胜感激 .

2 回答

  • 0

    考虑部分:

    $j('[id$="highlightPanelOpenRequiredItems"]').removeClass('glowed',duration,glowOpenItems(duration));
    

    我猜你应该把 glowOpenItems(duration) 放在一个内联函数中:

    $j('[id$="highlightPanelOpenRequiredItems"]').removeClass('glowed',duration,function(){glowOpenItems(duration);});
    

    此外,您不应该多次执行jQuery选择器 . 考虑将选定的jQuery对象分配给变量并重用它 .

  • 0

    递归中没有 base case . 所以简单地说它不会突破递归(无限递归) . 这就是为什么你得到最大的调用堆栈错误 . 尝试添加基本案例,您可以从递归中断 .

    在你的条件 '[id$="reqGlowPanel"]').length>0 && run == true 表达式中没有一个随着函数的执行而改变 . 所以如果他们是真的,他们会一直都是真的 .

    尝试这样的事情:(这只是一个逻辑,所以语法可能会出错 . )

    function glowOpenItems(duration){
    
                    duration--   //decrease your duration in each call
                    if(duration <= 0) 
                        return //the base case   
                    else
                        $('#dialog').addClass('glowed',duration, function(){ 
                        $(this).removeClass('glowed',duration,function()    {glowOpenItems(duration)});
                    });
    

相关问题