setTimeout inside for loop

richard picture richard · Nov 21, 2009 · Viewed 33.8k times · Source

I want a string to appear character-for-character with the following code:

function initText()
{
    var textScroller = document.getElementById('textScroller');
    var text = 'Hello how are you?';

    for(c = 0; c < text.length; c++)
    {
        setTimeout('textScroller.innerHTML += text[c]', 1000);
    }
}

window.onload = initText;

It's not working.. what am I doing wrong?

Answer

Soufiane Hassou picture Soufiane Hassou · Nov 21, 2009

Try something like this:

function initText()
{
    var textScroller = document.getElementById('textScroller');
    var text = 'Hello how are you?';

    var c = 0;
    var interval = setInterval(function() { 
                          textScroller.innerHTML += text[c]; 
                          c++; 
                          if(c >= text.length) clearInterval(interval);
                   }, 1000);

}

Note I added clearInterval to stop it when it's needed.