2012-07-25 74 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(); 
    }); 
}​