【问题标题】:Jquery Firefox/Firebug recursionJquery Firefox/Firebug 递归
【发布时间】:2012-07-25 20:50:57
【问题描述】:

我使用了这个 sn-p,它工作得很好,但是如果 firebug 控制台说“递归太多”,firefox/firebug 就会死掉。这是一篇有类似问题的帖子,我觉得没有正确解决Jquery Too Much Recursion Error

有没有办法让这个颜色动画连续循环而不产生这个递归问题?如果没有,我怎样才能让它在没有递归的情况下工作?指定距离结束还有多长时间?

$(document).ready(function() {
    spectrum();

    function spectrum(){
        var  hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' +  (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() *  256)) + ')';
        $('#welcome').animate( { backgroundColor: hue }, 1000);
        spectrum(); 
    }       
});

【问题讨论】:

  • 当你只想运行一个周期性任务时不要使用递归。尝试使用 setTimeout 或类似...

标签: jquery firefox recursion firebug


【解决方案1】:

您会尽快运行该函数,而不是在动画完成时运行。这会导致函数每秒可能运行数百次,从而给您带来递归问题:

$(document).ready(function() {

    spectrum();

    function spectrum(){
        var  hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' +  (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() *  256)) + ')';
        $('#welcome').animate( { backgroundColor: hue }, 1000, spectrum);
    }
});

【讨论】:

  • 或者简单地说:$('#welcome').animate( { backgroundColor: hue }, 1000, spectrum);... 不需要其他功能。
  • @FelixKling - 你像往常一样是对的,编辑它。 setInterval 也是另一种方法,但回调更好 IMO。
  • 我也在考虑setTimeout(或setInterval),但是由于动画应该在前一个完成后重新开始,所以使用回调似乎是必要的。我也很确定 jQuery 在内部使用setTimeout
【解决方案2】:

那是因为您的递归调用不断被触发,而不是在动画完成后被触发。而是将调用放在 animate 函数的回调中,例如:

spectrum();
function spectrum() {
    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
    $('#welcome').animate({
        backgroundColor: hue
    }, 1000, function() {
        spectrum();
    });
}​

【讨论】:

    猜你喜欢
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 2019-06-15
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多