Reputation: 1855
I am trying to cycle through a list of elements and give them a random colour. But I don't want them to use the same colour as the previous one.
Therefore I created a for loop inside of which a function is called to grab a color from an array. If the colour matches the previous color it doesn't return instead calls itself again to get another colour.
The issue is that every so often the class doesn't get added to an element. It seems that either the for loop isn't waiting on it to return and cycling to the next element or that I shouldn't be calling the function again from within itself. I'm not quite sure though, would be great if someone could help at all, here is what I have so far:
/**
* Return int between min and max
* @return number.
*/
function randomIntFromInterval(min, max) {
return Math.floor(Math.random()*(max-min+1)+min);
};
var app = {
init: function(){
var self = this;
this.colorPool = ['blue', 'orange', 'pink'],
this.items = document.querySelectorAll('.js-icon'),
this.oldColor = 'pink',
this.newColor;
for (i = 0; i < this.items.length; i++) {
// Add a Random Color Class.
self.newColor = self.getColor(self.oldColor);
self.items[i].classList.add(self.newColor);
}
},
getColor: function() {
var color = this.colorPool[randomIntFromInterval(0, (this.colorPool.length-1))];
console.log('n= ',color, ' old= ', this.oldColor);
if(color === this.oldColor){
console.log('need to choose another');
this.getColor();
} else {
console.log('return now');
this.oldColor = color;
return color;
}
}
}
app.init();
Upvotes: 0
Views: 38
Reputation: 33315
Here is your error: you need to return the recursive value. return this.getColor();
if(color === this.oldColor){
console.log('need to choose another');
return this.getColor();
} else {
console.log('return now');
this.oldColor = color;
return color;
}
In your function only the first time if it finds the right color it is returned. When you call the function again recursively it will not return the color anymore. Therefore when you use recursive function you need to return both the base case and the result of the call to itself.
Upvotes: 1