如何在javascript数组中使用split()和setTimeout()

如何在javascript数组中使用split()和setTimeout(),javascript,jquery,split,settimeout,Javascript,Jquery,Split,Settimeout,这可能有点令人困惑:S 如果有人能帮我把字符串数组拆分成字母。而不是用超时来记录。就像在DOS里一样 我可以用单个字符串来实现,但不能在数组中实现 这是我的密码: var text = new Array(); text[0] = "welcome ".split(''); text[1] = "how are u?".split(''); var delay = 20; for (var j = 0; j < text.length; j++) { var txt = text

这可能有点令人困惑:S

如果有人能帮我把字符串数组拆分成字母。而不是用超时来记录。就像在DOS里一样

我可以用单个字符串来实现,但不能在数组中实现

这是我的密码:

var text = new Array();
text[0] = "welcome ".split('');
text[1] = "how are u?".split('');
var delay = 20;
for (var j = 0; j < text.length; j++) {

    var txt = text[j];
    for (u = 0; u < txt.length; u++) {
        setTimeout(function () {
            $('div#console_div').append('<br />' + txt.shift());
        }, delay * j + 100);
    }
}
var text=new Array();
文本[0]=“欢迎”。拆分(“”);
文本[1]=“u如何?”。拆分(“”);
无功延迟=20;
对于(var j=0;j'+txt.shift());
},延迟*j+100);
}
}

我就是这样做的。使用递归函数代替
for
循环,该函数根据其在字符串上的位置使用不同的参数调用自身:

您遇到了典型的“循环中的闭包”问题。看一看。在执行超时回调时,
txt
指的是
text[1]
。尽管如此,所有的超时仍然会执行,因此您调用
txt.shift()
的频率比数组中的元素要高

另一个问题是,任何人都很难注意到100毫秒的延迟,所以你看不到任何增量。更糟糕的是,对于第一个阶段,所有超时都同时执行(几乎),因为
j
0
delay*j+100
将导致
100


您最好一个接一个地处理每个字母,而不是一次创建所有超时(注意,这是相同的,但更容易理解,因为它更干净)

var text=[…];
函数printLetter(短语索引、字母索引){
var word=文本[短语索引];
如果(字){
如果(字母索引===字长){
打印字母(短语索引+1,0);
}
否则{
var字母=单词[字母索引];
如果(信){
$('div#console _div')。追加('br/>'+字母);
setTimeout(函数(){
打印字母(短语索引,字母索引+1);
}, 200);
}
}
}
}
打印字母(0,0);

对不起,NHAHDH,您能更具体地说:S
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); });
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); });
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);