为了账号安全,请及时绑定邮箱和手机立即绑定

我在使用 setInterval 时遇到问题

我在使用 setInterval 时遇到问题

慕无忌1623718 2021-06-30 17:33:46
最近几天我一直在研究这个,它看起来很简单,但我无法让它正常工作。我试图每 10 秒显示一个关于兔子的事实。我已经编写了数组、循环和函数,但它只显示数组中的最后一项。var bunnyArr = ["Rabbits don't eat root vegetables, such as carrots", "baby rabbits are called kittens", "A group of rabbits are called a fluffel"];function bunnyStat() {    for (i = 0; i < bunnyArr.length; i++) {        document.getElementById('listItem1').textContent = bunnyArr[i]    }}setInterval(bunnyStat, 10000);它也没有给我任何错误,所以我不知所措。
查看完整描述

3 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

您的函数一次遍历所有数组,这就是为什么您只看到最后一个。


在函数外保留一个计数器并在每次调用时增加它:


var bunnyArr = ["Rabbits don't eat root vegetables, such as carrots", "baby rabbits are called kittens", "A group of rabbits are called a fluffel"];


var index = 0;

var total = bunnyArr.length;


function bunnyStat() {

    if (index == total) {

        index = 0;

    }

    document.getElementById('listItem1').textContent = bunnyArr[index++];

}


setInterval(bunnyStat, 10000);

<div id="listItem1"></div>


查看完整回答
反对 回复 2021-07-01
?
慕的地10843

TA贡献1785条经验 获得超8个赞

其他人给出了正确的答案。作为奖励,我随机化了数组,而不是在同一序列上循环。


  var lastBunnyStat = 0;

  var bunnyArr = [

    "Rabbits don't eat root vegetables, such as carrots",

    "Baby rabbits are called kittens",

    "A group of rabbits are called a fluffel",

    "Rabbits can turn their ears 180 degrees",

    "Their ears can pinpoint the exact location of a sound",

    "Rabbits don’t make good pals."

  ];

  bunnyArr.sort(function() {

        return 0.5 - Math.random();

  });

  // console.log(bunnyArr);


  function bunnyStat() {


    document.getElementById('listItem1').textContent = bunnyArr[lastBunnyStat++];

    if (lastBunnyStat >= bunnyArr.length) {

      lastBunnyStat = 0;

      bunnyArr.sort(function() {

          return 0.5 - Math.random();

      });

      // console.log('endofloop');console.log(bunnyArr);

    }

  }


  setInterval(bunnyStat, 1200);//change to 10000


查看完整回答
反对 回复 2021-07-01
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

这是因为bunnyStat()它非常快速地循环遍历数组的所有三个元素,并在最后一个元素上结束。试试这样的:


var lastBunnyStat = 0;

var bunnyArr = [

  "Rabbits don't eat root vegetables, such as carrots",

  "baby rabbits are called kittens",

  "A group of rabbits are called a fluffel"

];


function bunnyStat() {

  document.getElementById('listItem1').textContent = bunnyArr[lastBunnyStat++];

  if (lastBunnyStat >= bunnyArr.length) {

    lastBunnyStat = 0;

  }

}


setInterval(bunnyStat, 10000);


查看完整回答
反对 回复 2021-07-01
  • 3 回答
  • 0 关注
  • 156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信