Kwang Kwang - 3 months ago 7x
HTML Question

Changing color code doesn't work

function color(){
var color = "#"
for(var i = 0; i<6; i++){
color += Math.floor((Math.random()*16)).toString(16);
document.getElementsByTagName('body')[0].style.backgroundColor = color;

function change(){
setInterval(color(), 1000);

<!DOCTYPE html>
<button id='button' onmouseover="change();" style='width:50px; height:50px; margin-left:auto;'>click</button>
<script type="text/javascript" src='js.js'></script>

I tried to make the auto changing background coding.

I want to change the background color every 1 second.
but it just change color once when i put my mouse on.

what is the problem?


You're calling the function, not referencing it in the setInterval call.

Change it to

setInterval(color, 1000);


When you add the parentheses to a function, it's called, and the returned result, which is always undefined unless something else is defined in the called function, will be returned.

What you're doing is the same as

var fn = color(); // returns undefined

setInterval(fn, 1000); // undefined, 1000