2012-07-25 76 views
1

我拿了这个片段,它的效果很好,但如果萤火虫控制台说'太多递归',firefox/firebug会死亡。这里有一个类似的问题,我不觉得被正确解决Jquery Too Much Recursion ErrorJquery Firefox/Firebug递归

有没有办法让这种动画的颜色不断循环,而不会产生这种递归问题?如果没有,我怎么能让这个工作没有递归?指定一段时间直到结束?

$(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(); 
    }  
}); 
+0

当您只想运行周期性任务时,不要使用递归。用setTimeout或类似的方法尝试...... – Alfabravo 2012-07-25 20:54:05

回答

3

您正在尽快运行该功能,而不是动画完成时。这将导致功能可能运行数百次每秒,为您提供reccursion问题:

$(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); 
    } 
}); 
+1

或简单地说:'$('#welcome')。animate({backgroundColor:hue},1000,spectrum);'...不需要另一个函数。 – 2012-07-25 20:54:54

+0

@FelixKling - 你像往常一样正确,编辑它。 setInterval也是另一种方式,但回调是更好的IMO。 – adeneo 2012-07-25 20:56:53

+0

完美,谢谢你们两位! – RooWM 2012-07-25 21:03:08

0

那是因为你的递归调用不断被解雇掉,而不是在做了动画之后被解雇。取而代之的是将回调放入动画函数的回调中,例如:

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(); 
    }); 
}​