Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  28] [ 2]  / answers: 1 / hits: 49920  / 13 Years ago, wed, november 23, 2011, 12:00:00

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>

More From » html

 Answers
10

There are several problems here. I’ll just fix your code:



var x;

function changecolors() {
x = 1;
setInterval(change, 1000);
}

function change() {
if (x === 1) {
color = red;
x = 2;
} else {
color = green;
x = 1;
}

document.body.style.background = color;
}


Basically...




  • You need setInterval instead of setTimeout. setTimeout only executes once.

  • = assigns, even in an if statement. You need == (or better, ===).

  • You shouldn't pass a string to setTimeout or setInterval. 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:



window.onload = changecolors;


Of course, you could do it with fewer functions and no pollution of the global namespace.


[#88933] Tuesday, November 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
corie

Total Points: 371
Total Questions: 110
Total Answers: 113

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
corie questions
Mon, Feb 22, 21, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Sun, Jun 9, 19, 00:00, 5 Years ago
;