What you need is some sort of state or context. I.e., what color am I on, and what color comes next?
Typically, functions are a poor choice for this, because it means you have side effects. That is, the function changes the greater context of the program, and is no longer predictable. (Functions that return random results are generally okay because it's understood that they're unpredictable.)
One way to accomplish this is to use an object that has a method, which is the object-oriented approach to managing state:
function ColorProvider() {
this.colors = ['#4B3E4D', '#D74F33' /*...*/];
this.currentColorIndex = 0;
}
// gets the next color; returns "undefined" when all colors
// have been exhausted
ColorProvider.prototype.getNextColor = function() {
return this.colors[this.currentColorIndex++];
}
ColorProvider.prototype.reset = function() {
this.currentColorIndex = 0;
}
It's a lot of work for small functionality, but it is the "sane" (object-oriented) way to handle state-based function. You would use it like this:
var cp = new ColorProvider();
cp.getNextColor(); // returns '#4B3E4D'
cp.getNextColor(); // returns '#D74F33'
(Note that this, and the other implementations I'm suggesting, simply start returning undefined when there are no more colors. It would be easy enough to modify these examples so that they loop around and start again at the beginning.)
Another way to do it is to use a closure, which is similar to the object-oriented approach:
var getNextColor = (function() {
var currentColorIndex = 0;
var colors = ['#4B3E4D', '#D74F33' /*...*/];
return function() {
return colors[currentColorIndex++];
}
})();
Lastly, maybe you don't want a function at all...maybe you just want to have colors be an array that's lying around, and you can just iterate over it as needed:
var colors = ['#4B3E4D', '#D74F33' /*...*/];
// whenever you need it....
for(var i=0; i<colors.length; i++) {
colors[i]; // '#4B3E4D', '#D74F33', etc.
}
// or....
colors.forEach(function(c) {
// c takes on the values '#4B3E4D', '#D74F33', etc.
});
Math.floor(Math.random() * colors.length).