Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change text multiple times at different intervals?

So let's say you have something like this..

HTML:

<p id="text"></p>

JS:

setTimeout(function() {$('#text').html("First sentence");}, 1000);
setTimeout(function() {$('#text').html("Second sentence");}, 2000);

Is there any way you can display like ten of these sentences without having to write the same line of code ten times? I can't figure it out..

like image 235
user298519 Avatar asked Mar 12 '23 10:03

user298519


2 Answers

Create a closure over i and throw a party.

var $text = $("#text");
var numbers = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth"];

for (var i = 1; i <= 10; ++i) {
  (function(index) {
    setTimeout(function() { 
      $text.html(numbers[index-1] + " sentence");
    }, i * 1000);
  })(i);
}

enter image description here

https://jsfiddle.net/9z4r1qqk/

like image 65
Andy Hoffman Avatar answered Mar 16 '23 02:03

Andy Hoffman


Something like:

for(var i = 1; i < 10 ; i++) {
    setTimeout(function() {$('#text').html("Sentence #" + i);}, i * 1000);
}

If you don't need the sentence to have exactly that format.

like image 33
JohannThor Avatar answered Mar 16 '23 02:03

JohannThor