I'd like to change the color of the sqaure (#myID: width = height = 100px) every second. (To check if that switch loop works, in every "case" I wrote console.log("smth happened");.) But the color of this square does not change. "FIDDLE"
Next thing, every second document.getElementById('myID') is written to a new formed variable thesquare. How to make the variable global, outside the function?
Javascript:
var i = 0;
function changecolor()
{
var thesquare = document.getElementById('myID');
switch (i)
{
case 0 :
thesquare.setAttribute("background-color","red");
++i;
break;
case 1 :
thesquare.setAttribute("background-color","green");
++i;
break;
default :
thesquare.setAttribute("background-color","blue");
i=0;
break;
}
}
setInterval("changecolor()",1000);
It is not an attribute you want to set but a
style
:Your function does work but the attribute
background-color
does not do anything.Also,
setInterval("changecolor()",1000);
should besetInterval(changecolor,1000);
Fiddle
You don't need to use a global, you can keep it in an outer scope using a closure and an immediately invoked function expression (IIFE):
Note that setInterval will run at about, not exactly, the specified interval. It will slowly lose time.
You can shorten the code by replacing the entire switch block with something like: