0

Hi im new to javascript and im trying to figure out how to append a string after an allotted amount of time.

After 3 secs append string (How)
After 3 secs append string (are)
After 3 secs append string (you)
After 3 secs append string (?)

Thanks :D

1
  • Please heed @SLaks' comment and do not pass a string to setTimeout. It's eval in disguise. Commented May 4, 2011 at 2:55

3 Answers 3

3

Use setTimeout.

var text = 'How are you ?'.split(' '),
    delay = 3000;

function generateCallback(text) {
    return function () {
        alert(text);
    };
}

for (var i=0; i<text.length; i++) {
    setTimeout(generateCallback(text[i]), delay*(i+1));
}

http://jsfiddle.net/mattball/dYBUs/

Sign up to request clarification or add additional context in comments.

Comments

1
<html>
    <head></head>
    <body>
        <span id="mySpan"></span>
    </body>
    <script>
        setTimeout('document.getElementById("mySpan").innerHTML += "How ";', 3000);
        setTimeout('document.getElementById("mySpan").innerHTML += "are ";', 6000);
        setTimeout('document.getElementById("mySpan").innerHTML += "you";', 9000);
        setTimeout('document.getElementById("mySpan").innerHTML += "?";', 12000);
    </script>
</html>

2 Comments

Do not pass a string to setTimeout.
Please do not advise passing strings to setTimeout. It's eval in disguise.
0

As a modification of current answers, a single setInterval call can be used, cancelling it when all words are displayed:

// s is string to display
// interval is the time in milliseconds between adding words
// id is the id or reference to a DOM element to display s in
function staggerDisplay(s, interval, id) {

  var el = typeof id == 'string'? document.getElementById(id) : id;
  var sBits = s.split(' ');
  var numWords = sBits.length;
  var i = 0;
  var intervalRef = setInterval(
    function () {
      if (i < numWords) {
        el.innerHTML += ' ' + sBits[i++];
      } else {
        clearInterval(intervalRef);
      }
    }, interval);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.