6

こんにちは、私は Javascript の初心者です。ページ上のフレーズを自動入力し、しばらく一時停止し、div をクリアし、次のフレーズを自動入力するスクリプトをプログラムしました。継続的にループする必要があります。

私が見つけた JavaScript の wait() ソリューションを使用すると、問題が見つかりました。各フレーズが一時停止期間にある場合、ページ上の他のすべての JavaScript は無効になります。マルチスレッドが存在しないため、これはJavaScriptのブロックの問題によるものであることが調査されましたか? 私の状況を考えると、フレーズがクリアされる前に残ることを許可する解決策を見つけることができませんでしたが、ブロックすることもありません.

以下は私のコードです。何かアドバイス ?

var index = 0;
var phrases = new Array();

//add a new variable to the array to add new phrases
phrases[0] = "Type the first phrase.";
phrases[1] = "Type the second...";
phrases[2] = "Type the third...";

var split_chars = phrases[index].split("");

function type_phrases()
{  
    if(split_chars.length > 0) {
        document.getElementById('matrix_typer').innerHTML += split_chars.shift();
        }
        else {
        clearTimeout(loopTimer); 
        wait(10000);//add a delay before the next phrase is typed
        document.getElementById('matrix_typer').innerHTML = " ";   
        index += 1;

        if(index >= phrases.length)
        { 
         index = 0;
        }   
        split_chars = phrases[index].split("");     
        }
    loopTimer = setTimeout('type_phrases()',400);

}

function wait(ms) {
    var start = +(new Date());
    while (new Date() - start < ms);
}
4

2 に答える 2

2

2つの関数を使用し、遅延関数の代わりに別のタイムアウトを追加します

var phrases = new Array();

//add a new variable to the array to add new phrases
phrases[0] = "Type the first phrase.";
phrases[1] = "Type the second...";
phrases[2] = "Type the third...";

var index = 0;
var split_chars = phrases[index].split("");

function type_phrase()
{
    document.getElementById('matrix_typer').innerHTML = "&nbsp;"; 
    split_chars = phrases[index].split("");

    return type_char();
}

function type_char()
{
    if(split_chars.length > 0)
    {
        document.getElementById('matrix_typer').innerHTML += split_chars.shift();
    }
    else
    {
        clearTimeout(charloopTimer); 
        phraseloopTimer = setTimeout('type_phrases()',1000); //set a timeout instead of a delay
        index += 1;
        if(index >= matrix_phrases.length)
            index = 0;
    }
    charloopTimer = setTimeout('type_char()',400);
}
于 2013-02-13T03:37:54.437 に答える