开发者

Why doesn't this setInterval code work?

I'm trying to change the background color of the body every second but it does not work. What did I do wrong?

var colors = [
    "red", "blue", "green", "yellow", "red"
    ],
    rand = Math.ceil(Math.r开发者_开发问答andom() * colors.length - 1),
    t = setInterval(function() {
        document.body.style.backgroundColor = colors[rand];
    }, 1000);


You are defining the value rand once and then reusing it every time. You mean:

var colors = [
"red", "blue", "green", "yellow", "red"
];
t = setInterval(function() {
    // use floor instead of ceil and then you can skip the -1
    var rand = Math.floor(Math.random() * colors.length)
    document.body.style.backgroundColor = colors[rand];
}, 1000);

Also, you're using commas to separate the commands, while this won't always break (I can think of at least one situation where it won't), it is generally a bad idea because it implies that there is some larger structure going on.

As per patrick dw's comment, you are right to use commas. It caused me to have a mental slip-up in that context, especially when rand was moved into the setInterval's function. I would suggest that you might want to re-write that as var colors, t; colors = to help people understand more (at one point it looked like I was not the only one who made that mistake)


rand is only being set the once, try this:

var colors = [
    "red", "blue", "green", "yellow", "red"
    ],
    t = setInterval(function() {
        var rand = Math.ceil(Math.random() * colors.length - 1);
        document.body.style.backgroundColor = colors[rand];
    }, 1000);


Try the following

var colors = ["red", "blue", "green", "yellow", "red"];
t = setInterval(function() {
  var rand = Math.ceil(Math.random()) % colors.length;
  document.body.style.backgroundColor = colors[rand];
}, 1000);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜