user298519 user298519 - 1 year ago 46
Javascript Question

How to change text multiple times at different intervals?

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


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


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

Answer Source

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

enter image description here