user298519 user298519 - 2 years ago 69
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download