-2

I am trying to make a script that changes the header's color every second, I have made a function that styles a HTML element with a random color whenever it's called, and when I use the setInterval(); it does not work!

function randomColor(elementId) {
var colors = ["red","green","blue","purple","lightblue","cyan","yellow","brown","pink","grey"];
var randomNumber = Math.floor(Math.random() * 10) + 1;
document.getElementById(elementId).style.color = colors[randomNumber];
}

setInterval(randomColor("Header"), 1000);

Can someone help? thanks!

Note: When I refresh the page it only changes the color once.

Anonymous
  • 13
  • 4

3 Answers3

3

It's because you are calling randomColor and the result to that function is being passed into setInterval.

You should be able to pass a wrapped version in just fine:

setInterval(function() { randomColor("Header"); }, 1000);
halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
2

The setInterval function takes as input a function. In your example, you are executing randomColor("Header") and sending the result to the setTimer function.

setInterval(function() { randomColor("Header") }, 1000);
dana
  • 17,267
  • 6
  • 64
  • 88
1

You should send a function as arugment in setInterval, like this:

setInterval(function(){randomColor("Header")}, 1000);
Antony
  • 1,253
  • 11
  • 19
Man Programmer
  • 5,300
  • 2
  • 21
  • 21