问题
I hope someone could help me.
I have this code:
<script>
$(document).ready(function() {
spectrum();
function spectrum(){
$('#bottom-menu ul li.colored a').animate( { color: '#E7294F' }, 16000);
spectrum2();
}
function spectrum2(){
$('#bottom-menu ul li.colored a').animate( { color: '#3D423C' }, 16000);
spectrum();
}
});
</script>
it's working but when I look at firebug it says that there's a Too Much Recursion error.
I hope someone can tell me why.
Thanks!
回答1:
The problem is that your script never stops executing.
When the page loads, you tell it to run the function spectrum()
. It runs this function, and is then told to run the function spectrum2()
, which it does. When it finishes spectrum2()
, you tell it to run spectrum()
again, and when it's done that it has to run spectrum2()
yet again.. see the pattern? Your poor script is stuck executing those two functions over and over, forever!
The process of a function calling itself (or two functions calling each-other repeatedly) is called recursion, but normally the recursion ultimately terminates in some way. Yours never terminates, so FireBug says "Wait a minute, this script is never going to end, I'd better throw an error!"
This probably isn't what you're trying to achieve, and the fix is most likely simple. If you could try and explain what you're trying to achieve, maybe we can help you write the proper code?
回答2:
You have a clear endless recursion. specturm() calls spectrum2() which in turn calls spectrum(); you do not have a condition for terminating. You need to add a condition to terminate that recursion. Perhaps you want to achieve the following. If you let us know what you are trying to achieve, then you will get a solution.
<script>
$(document).ready(function() {
spectrum();
function spectrum(toEnd){
$('#bottom-menu ul li.colored a').animate( { color: '#E7294F' }, 16000, function(){
if(!toEnd)
spectrum2(true);
});
}
function spectrum2(toEnd){
$('#bottom-menu ul li.colored a').animate( { color: '#3D423C' }, 16000, function(){
if(!toEnd)
spectrum(true);
});
}
});
</script>
回答3:
use setTimeout to remove the calling functions from the stack:
function spectrum(){
$('#bottom-menu ul li.colored a').animate( { color: '#E7294F' }, 16000);
setTimeout(function() {spectrum2();},100);
}
this way, spectrum has a chance to finish while you start spectrum2. Do same with spectrum2.
来源:https://stackoverflow.com/questions/3043970/jquery-too-much-recursion-error