I’m trying to make a webpage change the background color every one second using JavaScript.
I’m using setTimeout but I can’t figure out how to get my variable to change in the function. Here’s my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function changecolors() {
x = 1; // <-- I know this is wrong, I just don't know where to place it
var t = setTimeout("change()", 1000);
}
function change() {
while(x < 3) {
if(x = 1) {
color = "red";
x++;
} else if (x = 2) {
color = "green";
x = 1;
}
document.body.style.background = color;
}
}
</head>
<body onload="changecolors()">
</body>
</html>
There are several problems here. I’ll just fix your code:
Basically…
setIntervalinstead ofsetTimeout.setTimeoutonly executes once.=assigns, even in anifstatement. You need==(or better,===).setTimeoutorsetInterval. Instead, pass a function.Another point of note: you shouldn’t use the
on*attributes of HTML elements for event listeners, but especially not on<body>, since you can do this in JavaScript instead, and be unobtrusive:Of course, you could do it with fewer functions and no pollution of the global namespace.