Reputation: 278
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
Upvotes: 0
Views: 2985
Reputation: 147473
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);
}
Upvotes: 0
Reputation: 359966
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/
Upvotes: 3
Reputation: 54846
<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>
Upvotes: 1