Reputation: 49
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.
Upvotes: 1
Views: 218
Reputation:
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>
Upvotes: 2
Reputation:
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>
Upvotes: 1
Reputation: 371
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
Upvotes: 2