これは私がそれを行う方法です。ループの代わりにfor
、文字列のどこにあるかに応じて異なる引数で自分自身を呼び出す再帰関数を使用します。
var text = new Array();
text[0] = "welcome ".split('');
text[1] = "how are you?".split('');
var delay = 400;
function addOneChar(i, j) {
$('#console_div').append('<br>' + text[i][j]);
if (j+1<text[i].length) { // next character in the current string
setTimeout(function() { addOneChar(i, j+1); }, delay);
} else if (i+1<text.length) { // start the next string in the text[] array
setTimeout(function() { addOneChar(i+1, 0); }, delay);
} // else quit
}
setTimeout(function() { addOneChar(0,0); });
http://jsfiddle.net/mblase75/tkEDN/
text[]
単一の文字列に結合し、文字.charAt()
を抽出するために使用することで、これをさらに簡素化できます。
var text = new Array();
text[0] = "welcome ";
text[1] = "how are you?";
var delay = 400;
var textstr = text.join('');
function addOneChar(i) {
$('#console_div').append('<br>' + textstr.charAt(i));
if (i+1<textstr.length) {
setTimeout(function() { addOneChar(i+1); }, delay);
} // else quit
}
setTimeout(function() { addOneChar(0); });
http://jsfiddle.net/mblase75/MYtjy/