You have the typical "closure in a loop" problem. Have a look at JavaScript closure inside loops – simple practical example. At the moment the timeout callbacks are executed, txt
refers to text[1]
. All the timeouts are still executed though, so you are calling txt.shift()
more often than there are elements in the array.
Another problem is that any delay up to 100ms is hardly noticeable by any human being, so you don't see any increment. Even worse, for the first phrase, all timeouts are executed at the same time (nearly), since j
is 0
and delay * j + 100
will result in 100
.
You are better off processing each letter one by one instead of creating all the timeouts at once (note that Blazemonger's solution is the same, but easier to understand since it is cleaner).
var text = [...];
function printLetter(phrase_index, letter_index) {
var word = text[phrase_index];
if (word) {
if (letter_index === word.length) {
printLetter(phrase_index + 1, 0);
}
else {
var letter = word[letter_index];
if (letter) {
$('div#console_div').append('<br />' + letter);
setTimeout(function() {
printLetter(phrase_index, letter_index + 1);
}, 200);
}
}
}
}
printLetter(0, 0);
DEMO