如何在JavaScript中“等待”而不阻塞(忙等待)?

时间:2013-02-13 03:14:54

标签: javascript thread-sleep

嗨,我是一个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);
}

2 个答案:

答案 0 :(得分:4)

使用setTimeout

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

}, 1000);

参考JavaScript.setTimeout

答案 1 :(得分: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);
}