user2700923
user2700923

Reputation:

Loading "..." loop, with changing text every 3 seconds

JSFiddle: http://jsfiddle.net/6A7xh/1/

The purpose of this script is to output

Loading.

[1 second delay] ->

Loading..

[1 second delay] ->

Loading...

[1 second delay] ->

Painting Mona Lisa.

[1 second delay] ->

Painting Mona Lisa..

[ and so on ]


So here's the stuff:

 loadList = [
    "Loading the good stuff",
    "Painting Mona Lisa",
    "Just a second longer",
    "Or not",
    "Oh! We forgot to plug it in",
    "That's better",
    "Well",
    "Maybe not",
    "Wondering why",
    "your internet is so slow",
    "Still",
    "Loading",
];


var i = 0;
var x = 0;

function loadTrans(x){
        //if (!$(window).ready){
            $(".intro > p").text(loadList[x]);
            playTrans();
        //}
}

function playTrans(){
    currentText = $(".intro > p").text();
    setTimeout(function(){
        $(".intro > p").text( currentText + ".");
        if(i == 3){
            x++;
            loadTrans(x);
        }
        i++;
        if(i < 4){
            playTrans();
            i = 0;
        }

    },1000);
}

loadTrans();

I think what I'm trying to do is clear, but it appears my method is failing so far. Right now, the script is adding the periods in a never ending loop, and the transitions aren't happening every third loop.

What am I doing wrong here? Does anyone know a way I could do this more neatly?

Note: I originally did this with a for loop, but setTimeout obviously fails in that situation.

Upvotes: 0

Views: 820

Answers (2)

user1636522
user1636522

Reputation:

One problem :

i++;
if (i < 4) { 
    i = 0; // i : 0, 1, 0, 1...
}

Upvotes: 0

Joseph
Joseph

Reputation: 119847

You can do this. You can put this in a function, and the timer in a variable. When your resources are all loaded, you can use clearInterval to clear the timer.

 var i = 0;
 var textarea = $('.intro p');

 var loadTimer = setInterval(function () {
     if (i % 4 === 0) textarea.text(loadList[i / 4]); //change text after 3 steps
     else textarea.text(textarea.text() + '.');       //add period
     ((i / 4) < loadList.length) ? i++ : i = 0;       //back to start
 }, 500);

Upvotes: 2

Related Questions