简体   繁体   English

如何在 JavaScript/HTML 中一次又一次地重复数组列表中的项目

[英]How to repeat the items in array list again and again in JavaScript/HTML

I am trying to display text from the array one by one on my website, i'm able to do it once but i wish to repeat the list again and again (start over) as long as the user keep the page open.我正在尝试在我的网站上一个一个地显示数组中的文本,我能够一次完成,但我希望一次又一次地重复列表(重新开始),只要用户保持页面打开。

The below code works without while loop but only once:下面的代码没有 while 循环但只有一次:

<h1 id="looper" ></h1>

<script>
var i = ["ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ", "Hello", "hola", "नमस्ते", "你好!", "Здравствуйте"];
for( var j = 0 ; j < i.length; j++ ) {
  setTimeout( (function(j){ return function(){$("#looper").text(i[j]);}})(j), j*1000 );
}
</script>

But when i use while loop the browser gets overloaded or freezes.但是当我使用 while 循环时,浏览器会超载或死机。

  while(true){
  for( var j = 0 ; j < i.length; j++ ) {
  setTimeout( (function(j){ return function(){$("#looper").text(i[j]);}})(j), j*1000 );
   }
  };

I'm working with Django, in case if it can be done using python as well.我正在使用 Django,以防它也可以使用 python 来完成。

You could use setInterval instead of setTimeout like so:您可以像这样使用setInterval而不是setTimeout

<script>
var i = ["ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ", "Hello", "hola", "नमस्ते", "你好!", "Здравствуйте"];
for( var j = 0 ; j < i.length; j++ ) {
  //vvvvv THIS CODE CHANGED vvvvv
  setInterval( (function(j){ return function(){$("#looper").text(i[j]);}})(j), j*1000 );
}
</script>

The reason for this is setTimeout sets a function to be run once, while setInterval will make it run over and over like you want这样做的原因是setTimeout将 function 设置为运行一次,而setInterval将使它像你想要的那样一遍又一遍地运行

Please try this one.请试试这个。 It is working on my side.它在我这边工作。


<h1 id="looper" ></h1>

    <script>
    var i = ["ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ", "Hello", "hola", "नमस्ते", "你好!", "Здравствуйте"];

        setInterval(function(){
            for( var j = 0 ; j < i.length; j++ ) {
                setTimeout( (function(j){ return function(){$("#looper").text(i[j]);}})(j), j*1000 )
            }
        }, 1000 * i.length);
        
    </script>


You have to use setInterval function..你必须使用 setInterval function..

<h1 id="looper" ></h1>

<script>
var i = ["ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ", "Hello", "hola", "नमस्ते", "你好!", "Здравствуйте"];
setInterval(function(){
  for( var j = 0 ; j < i.length; j++ ) {
    setTimeout( (function(j){ return function(){$("#looper").text(i[j]);}})(j), j*1000 );
  }, 1000 * i.length);
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM