Reputation: 37
I tried to split alle letters and display one by one with timeout. I found some solution but they seem not working for me.
This script appends a complete layer (word) but jumps over the each loop. The message is a string named Hello!
Plugin.prototype.message = function(message) {
var word = '<div class="word">';
var letters = message.toString().split('');
$.each(letters, function (i, letter) {
//alert displays letter properly one by one
setTimeout(function () {
word += letter;
}, 30);
});
word += '</div>';
$('#chat-layer').append(word);
$('.word').animate({
opacity: 1
}, 200 );
}
Has anybody an idea, how to solve this?
Upvotes: 2
Views: 111
Reputation: 722
I just make this code to demonstrate chained executing of timers for letter by letter output (in your example all timers will be scheduled asynchronously after 30 ms from the one moment).
<html>
<body>
<div id="output">
</div>
<script>
var str = new String("The new string to display letter by letter"); // display this string
var interval = 500; // interval for each letter in ms
var letters = str.split("");
var cnt = 0;
var f = function(){
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + (letters[cnt] == " " ? " " : letters[cnt]);
if (cnt++<(letters.length-1)) {
setTimeout(f, interval);
}
}
f(); // first invoke
</script>
</body>
</html>
Upvotes: 1