设置javascript随机数发生器的计时器

时间:2015-04-09 17:48:26

标签: javascript setinterval

随机数发生器有效,但是想找到一种方法让它使用setInterval循环,这样它就可以在网站上自己的div中连续运行。

<script language="JavaScript">
setInterval(quotes(), 3000);
function quotes(i) {
    var r_text = new Array();
    r_text[0] = "All the leaves are brown";
    r_text[1] = "And the sky is grey";
    r_text[2] = "I've been for a walk";
    r_text[3] = "On a winter's day";
    r_text[4] = "I'd be safe and warm";
    r_text[5] = "If I was in L.A.";
    r_text[6] = "California dreaming, On such a winter's day";
    var i = Math.floor(7 * Math.random())
    document.write(r_text[i]);
}
</script>

5 个答案:

答案 0 :(得分:0)

setInterval(quotes(), 3000);更改为setInterval(quotes, 3000);

答案 1 :(得分:0)

您需要修复setInterval调用函数

更改

 setInterval(quotes(), 3000);

  setInterval(quotes, 3000);

并且该函数将每3秒随机化一次

编辑:此外,不推荐使用document.write(),并且应该使用其他函数替换它来写入html。

第二次编辑:您还传递了一个从未使用过的参数。考虑删除它。

答案 2 :(得分:0)

SetInterval需要一个函数调用,调用中的括号使它执行该函数并将值返回给setInterval。此外,您不需要“i”作为参数。

尝试:

setInterval(quotes, 3000);
function quotes() {
    var r_text = new Array();
    r_text[0] = "All the leaves are brown";
    r_text[1] = "And the sky is grey";
    r_text[2] = "I've been for a walk";
    r_text[3] = "On a winter's day";
    r_text[4] = "I'd be safe and warm";
    r_text[5] = "If I was in L.A.";
    r_text[6] = "California dreaming, On such a winter's day";
    var i = Math.floor(7 * Math.random())
    document.write(r_text[i]);
}

答案 3 :(得分:0)

你的setInterval不正确。

setInterval(function(){quotes()}, 3000);

function quotes() {
    var r_text = new Array();
    r_text[0] = "All the leaves are brown";
    r_text[1] = "And the sky is grey";
    r_text[2] = "I've been for a walk";
    r_text[3] = "On a winter's day";
    r_text[4] = "I'd be safe and warm";
    r_text[5] = "If I was in L.A.";
    r_text[6] = "California dreaming, On such a winter's day";
    var i = Math.floor(7 * Math.random())   
    document.write(r_text[i]);
}

答案 4 :(得分:0)

var quotes = [
  "All the leaves are brown",
  "And the sky is grey",
  "I've been for a walk",
  "On a winter's day",
  "I'd be safe and warm",
  "If I was in L.A.",
  "California dreaming, On such a winter's day"
];

function getRandomQuote() {
  var index = Math.random() * quotes.length << 0;
  return quotes[index];
}

setInterval(function() {
  var quote = getRandomQuote();
  document.write(quote);
}, 3000);

这种方式将代码分成逻辑部分;有一个函数来获取随机引用,以及一个匿名函数(在setInterval内)到document.write它。您也可以使用数组速记来定义引号,而不是单独定义每个引号(并且每隔3秒重新定义它们,就像其他答案那样)。

<< 0只是快速切断(注意:不会舍入)Javascript中数字的小数。