Reputation: 45
I want to make a simple iterate array with for. But can't make that script work... If anyone can give directions to self study, I appreciate any idea!
var colors = ['green', 'red', 'blue', 'grey', 'orange'];
function chColor(){
setInterval(
function(colors){
for(var i = 0; i <= colors.lenght; i++){
document.body.style.backgroundColor = Colors[i];
}},3000)}
(function(){setTimeout(function(){chColor()},3000);})();
Upvotes: 0
Views: 1607
Reputation: 386560
You could take an index for the colors and increment after every interval and adjust with remainder operator and length of the array.
Your issues:
Interval with a function with an argument, this paramter is never handed over, so it is undefined
.
for
loop in interval which iterates straight on and end at the end with a used
array Colors
which does not exist. Javascript is a case sensitive language.
Because of the for
loop, the final color, if the right array would be taken, is always the same.
Unclear use of setTimeout
which defers the call of chColor
by 3 seconds. The first change of color is anther 3 seconds later ...
function chColor(colors, i) {
setInterval(
function() {
document.body.style.backgroundColor = colors[i];
i++;
i %= colors.length;
},
3000
);
}
var colors = ['green', 'red', 'blue', 'grey', 'orange'];
chColor(colors, 0); // take colors as array and start with index zero
Upvotes: 2
Reputation: 13014
Lot of corrections needed. Find inline comments below:
var colors = ['green', 'red', 'blue', 'grey', 'orange'];
function chColor(){
setInterval(
function(){ // do not pass colors in the method here, global colors should be used.
for(var i = 0; i < colors.length; i++){ // i should be < colors.length, it's 0 indexed.
console.log(colors[i])// should be colors[i] not Colors[i]
}},1000)}
(function(){setTimeout(chColor,1000);})(); // don't really need to make a blank function and call chColor, passing the function name will do. it's a callback
PS: Shortened the time to 1s for this example.
Edit: If you want to change color between every n seconds:
var colors = ['green', 'red', 'blue', 'grey', 'orange'];
function chColor(){
var i = 0;
setInterval(function(){
document.body.style.backgroundColor = colors[i];
i = (i+1) % colors.length; // increment i and cycle through loop
},1000)
}
(function(){setTimeout(chColor,1000);})();
Upvotes: 1