samedi 15 février 2020

Show 3 random colors at once every 4 seconds with jQuery

I have this code and I'm trying to show 3 random colors from an array, at once, every 4 seconds, but instead I get 1 color every 4 seconds, even if they are properly randomized...

What am I missing?

//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
    return colors.reduce((memo, val, index) => {
        var p = (n-memo.length); // How many remaining to choose.
        var q = colors.length-index; // How many remaining to choose from.
        if (Math.random() < p/q){
            memo.push(val);
        }
        return memo;
    }, []);
};

//output the colors on the HTML
var counter = 0; //start counter
var elem = document.getElementById("changeText");//the place where we change things
setInterval(change, 4000);//every 4 seconds run the following stuff:
function change() {
 var text = three_random_colors(3);//get what's inside "three_random_colors"
 elem.innerHTML = text[counter];//on div, add content <--- (I want 3 at once here! but I get only 1)
    counter++;
    if(counter >= text.length) { counter = 0; var text = three_random_colors(3); }//reset
}



Aucun commentaire:

Enregistrer un commentaire