0

I can't find out where is the problem on this code:

<script>
    var colori = ['ffffff', 'ffbf00', 'ff4000', '4d79ff', '00c0ff', '00ff3f', 'ff7a4d', '00ff40', 'bf00ff', 'ff0040', 'ffd34d', 'a52a2a', 'bf00ff', '47adcf', '2a82a0' ];
    var i;

    function CambiaColore(){
        i = Math.floor(Math.random() * colori.length);
        var colore = '#'+colori[i];
        document.body.style.background=colore;
        setTimeout(CambiaColore(),2000);
    };

    CambiaColore();
</script>   

Can somebody explain me what's wrong?

Sir Von Berker
  • 330
  • 5
  • 11

2 Answers2

4

setTimeout(CambiaColore(),2000); wrong

setTimeout( CambiaColore, 2000 ); right

Explanation:

SetTimeout's first argument should be function. And you got it. But brackets after function name means its execution (my bad english, ya). Thus in your case it comes to recursion and that's all. Maximum stack calls, error.. So I as understood, you don't need to execute func there but postpone its execution. Correct way to do this I showed above.

Novelist
  • 469
  • 4
  • 15
1

Another possibility is to wrap it in an anonymus function:

setTimeout ( function(){ CambiaColore() } , 2000 ) ;
Radu Bogdan
  • 494
  • 2
  • 10