简体   繁体   中英

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:

<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(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.

You could use setInterval instead of setTimeout like so:

<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

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..

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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