1

我拿了这个片段,它工作得很好,但是如果萤火虫控制台说“递归过多”,火狐/萤火虫就会死去。这是一篇有类似问题的帖子,我觉得没有正确解决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(); 
    }       
});
4

2 回答 2

3

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

$(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);
    }
});
于 2012-07-25T20:53:29.863 回答
0

那是因为您的递归调用不断被触发,而不是在动画完成后被触发。而是将调用放在 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();
    });
}​
于 2012-07-25T20:53:56.713 回答