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

4

使用 setTimeout

setTimeout(function() {
  // do something 1000ms later here.

}, 1000);

参考JavaScript.setTimeout

于 2013-02-13T03:17:45.140 回答
2

use two functions and add another timeout instead of your delay function

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 回答