代码之家  ›  专栏  ›  技术社区  ›  Brian Duncan

如何在for循环内使用setTimeout更改div内容?

  •  0
  • Brian Duncan  · 技术社区  · 7 年前

    <p class="header">Head 1</p>
    
    <script>
        var changeThis = document.getElementsByClassName("header");
        for(i=0;i<10000;i++){
            setTimeout(function() {
                changeThis[0].innerHTML = "Head 2";
            },5000)
            setTimeout(function() {
                changeThis[0].innerHTML = "Head 3";
            },10000)
            setTimeout(function() {
                changeThis[0].innerHTML = "Head 4";
            },15000)
            setTimeout(function() {
                changeThis[0].innerHTML = "Head 1";
            },20000)
        }
    </script>
    
    3 回复  |  直到 7 年前
        1
  •  3
  •   Andrew Lohr    7 年前

    看来你宁愿用 setInterval

    这里有一个例子,我的意思是,它将继续循环,因为你想。

    var changeThis = document.getElementsByClassName("header");
    var headIndex = 2;
    
    function change() {
      changeThis[0].innerHTML = "Head " + headIndex;
      headIndex++;
    }
    
    // run change function every 3 seconds
    setInterval(change, 3000);
    <p class="header">Head 1</p>
        2
  •  2
  •   DarkPurple141    7 年前

    setInterval ,请注意,如果您希望它遍历头1、头2、头3等,则最好使用以下内容:

    const elements = ["head1", "head2"...]
    
    let currentIndex = 0
    const INTERVAL_LENGTH = 5000
    
    setInterval(() => {
        changeThis[0].innerHTML = elements[(currentIndex++)%elements.length]
    }, INTERVAL_LENGTH)
    
        3
  •  0
  •   Brian Duncan    7 年前

    感谢@Andrew_Lohr(和其他人)指出setInterval。最后,我使用的代码如下:

    var changeThis = document.getElementsByClassName("header");
    
    var headIndex = 1;
    
    var headTitles = ["Head 1", "Head 2", "head 3", "Head 4"];
    
    function change() {
        changeThis[0].innerHTML = headTitles[headIndex];
        headIndex++;
        if(headIndex > 3){
            headIndex=0;
        }
    }
    
    setInterval(change, 5000);