jquery - 使用 jQuery 每 4 秒显示 3 种随机颜色

标签 jquery random setinterval

我有这段代码,我试图每 4 秒一次从数组中显示 3 种随机颜色,但我每 4 秒得到 1 种颜色,即使它们是正确的随机...

我错过了什么?

//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
}

最佳答案

您的问题是您的 change 函数一次仅输出一种颜色。您可以将其简化为仅输出(例如)

text.join(' ')

您将看到所有三种颜色:

//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 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.join(' '); //on div, add content <--- (I want 3 at once here! but I get only 1)
}
<div id="changeText"></div>

关于jquery - 使用 jQuery 每 4 秒显示 3 种随机颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60244721/

相关文章:

python - Python的随机性的随机性

Javascript 函数 setInterval() 只工作一次

使用计时器调用 JavaScript 函数无法正常工作

javascript - jQuery : progress bar show in html

javascript - jQuery "$ is not a function"错误

jQuery 根据类重新排序列表项

jquery - 需要时动态加载/删除 CSS

大文件中的 Python 随机 N 行(无重复行)

c# - 将小 C# "Random String"函数转换为 Haskell 时遇到问题

javascript - 为什么 setTimeout 没有运行? (作用域链)