-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

Its 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);
Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
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
  • 16,055
  • 4
  • 61
  • 85
1

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

setInterval(function(){randomColor("Header")}, 1000);
Antony
  • 1,163
  • 9
  • 18
Man Programmer
  • 5,150
  • 2
  • 17
  • 18