robrob
robrob

Reputation: 43

How to repeat a sentence in jquery

I have this jquery script which reveals each word in a sentence one by one.

http://jsfiddle.net/9tvd3ybg/

$(function (){    

var str = "It was a dark and stormy night in the Bay of Biscay, and the Captain and his sailors were seated around the fire. Suddenly, one of the sailors said, Tell us a story, Captain. And the Captain began, ";

var spans = '<span>' + str.split(/\s+/).join(' </span><span>') + '</span>';

$(spans).hide().appendTo('.text').each(function(i){
        $(this).delay(100 * i).fadeIn(100);

});

});

I want the sentence to repeat over and over, appending to the end each time, ie.

It was a dark and stormy night in the Bay of Biscay, and the Captain and his sailors were seated around the fire. Suddenly, one of the sailors said, Tell us a story, Captain. And the Captain began, It was a dark and stormy night in the Bay of Biscay, and the Captain and his sailors were seated around the fire. Suddenly, one of the sailors said, Tell us a story, Captain. And the Captain began, .......

Not sure how to achieve this. I've tried .promise and .delay with no success. Any help would be appreciated, thanks.

Upvotes: 4

Views: 115

Answers (2)

jnthnjns
jnthnjns

Reputation: 8925

Here is a simple timeout using the code you provided:

var populateSentence = function () {
    $(spans).hide().appendTo('.text').each(function (i) {
        $(this).delay(100 * i).fadeIn(100);
        if (i === ($(spans).length - 1)) {
            setTimeout(function () {
                populateSentence();
                // timeout set to account for fade in delay
            }, $(spans).length * 100);
        }
    });
};
populateSentence();

Here is a Fiddle

Upvotes: 3

Taconut
Taconut

Reputation: 989

Try this:

var str = "It was a dark and stormy night in the Bay of Biscay, and the Captain and his sailors  were seated around the fire. Suddenly, one of the sailors said, Tell us a story, Captain. And the Captain began, ".split(/\s/);

var i = 0;
setInterval(function() {
    $('<span></span>').text(str[i]).hide().appendTo('.text').fadeIn(100);
    i = (i + 1) % str.length;
}, 100);

Upvotes: 1

Related Questions