Pure Javascript - Setinterval (1s), Setattribute
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');.
Solution 1:
It is not an attribute you want to set but a style
:
thesquare.style.backgroundColor = 'red';
Your function does work but the attribute background-color
does not do anything.
Also, setInterval("changecolor()",1000);
should be setInterval(changecolor,1000);
Solution 2:
Next thing, every second document.getElementById('myID') is written to a new formed variable thesquare. How to make the variable global, outside the function?
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):
(function() {
var thesquare = document.getElementById('myID');
var i = 0;
functionchangecolor() {
switch (i) {
case0 :
thesquare.style.backgroundColor = "red";
++i;
break;
case1 :
thesquare.style.backgrounColor = "green";
++i;
break;
default :
thesquare.style.backgroundColor = "blue";
i=0;
break;
}
}
setInterval(changecolor, 1000);
}());
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:
var colours = ['red','green','blue']
thesquare.style.backgroundColor = colours[i++ % colours.length];
Post a Comment for "Pure Javascript - Setinterval (1s), Setattribute"