所以我的主要目标是在单击按钮后每1秒随机化背景一次。 问题是我在控制台输出时每秒获得随机RGB,但是背景仅在上次迭代后才更改。
function random_background(){
var i;
for(i = 0; i < 3; i++){
let red = Math.floor(Math.random() * 256);
let green = Math.floor(Math.random() * 256);
let blue = Math.floor(Math.random() * 256);
let randomcolor = "rgb(" + red + "," + green + "," + blue + ")";
console.log(randomcolor);
document.body.style.background = randomcolor;
sleep(1000);
}
}
答案 0 :(得分:2)
Javascript没有任何睡眠方法。要在x次后重复调用函数,可以使用function random_background() {
let red = Math.floor(Math.random() * 256);
let green = Math.floor(Math.random() * 256);
let blue = Math.floor(Math.random() * 256);
let randomcolor = "rgb(" + red + "," + green + "," + blue + ")";
document.body.style.background = randomcolor;
}
setInterval(random_background, 1000);
public class Main {
public static void main(String[] args) {
int count;
boolean[] used;
used = new boolean[365];
count = 0;
while (true) {
int birthday; // The selected birthday.
birthday = (int) (Math.random() * 365);
count++;
if (used[birthday]) {
// This day was found before; It's a duplicate.
break; }
used[birthday] = true; }
System.out.println("A duplicate birthday was found after "
+ count + " kids came to the class.");
// double[] arr = {Numbers};
// double total = 0;
//for(int i=0; i<arr.length; i++){
// total = total + arr[i];
//}
//double average = total / arr.length;
// System.out.format("The average is: %", average);
}
答案 1 :(得分:0)
使用setinterval
代替sleep
使浏览器有机会做其他事情。例如,更新显示
答案 2 :(得分:0)
Javascript中没有sleep
函数。您应该使用setInterval
来运行函数,直到清除间隔且间隔为1秒为止。
此外,我不明白为什么在这里需要for
循环,所以我将其删除。
let interval = setInterval(() => {
let red = Math.floor(Math.random() * 256);
let green = Math.floor(Math.random() * 256);
let blue = Math.floor(Math.random() * 256);
let randomcolor = "rgb(" + red + "," + green + "," + blue + ")";
document.body.style.background = randomcolor;
}, 1000);