【问题标题】:setTimeout for nested if condition in for loopsetTimeout for for 循环中的嵌套 if 条件
【发布时间】:2013-11-26 13:21:08
【问题描述】:

我对 setTimeout 命令有点困惑。以下代码获取文本并返回 console.log() 字段中的单个单词。当然,这个过程是立即计算的。我想 setTimeout 这个过程,所以代码会给我例如每秒一个字。我有点纠结于 for 循环中的嵌套 if 条件,没有设法在这个板上找到解决方案或自己编写代码。

如果你能帮助我,那就太棒了。非常感谢。 :)

罗伯特

text = "test text bla blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var space = " ";
var h = 0;
var hits = [];
var word;


for (var h=0; h < text.length ; h++){

       if (text[h]== space){

       h=h+1;
       console.log(word);
       hits=[];

       }


hits.push(text[h]);
var word = hits.join("");

}

if (h=text.length)
       {
       console.log(word);
       }

【问题讨论】:

    标签: javascript loops for-loop nested settimeout


    【解决方案1】:
    • 按间距分割.split(' ');
    • 使用setInterval();
    • 完成后clearInterval();

    结果:

    var text = 'Powder gummies muffin jelly-o jelly cookie chocolate bar pudding';
    
    var words = text.split(' ');
    var i = 0;
    
    var interval = setInterval(function(){
      var word = words[i];
      if(word) {
        console.log(word);
        i++;
      } else {
        clearInterval(interval);
      }
    },1000);
    

    【讨论】:

    • 如果您知道所有命令,就会发生这种情况。 ;) 感谢代码(和拆分)。
    【解决方案2】:

    试试这个:

    var text = "one two three four five blah1 blah2 blah3";
    
    var words = text.split(" "); // split the text into an array of words
    var pointer = 0; // a pointer to keep track of which word we are up to
    
    var displayNextWord = function()
    {
        var word = words[pointer++]; // get the current word, then increment the pointer for next time
        if (word)
        { // if we haven't reached the end of the text yet...
            console.log(word); // print the word
            setTimeout(displayNextWord, 1000); // and try again in 1 second
        }
    }
    
    displayNextWord(); // knock down the first domino...
    

    Working example: JSFiddle.

    您发布的大多数示例代码都是您自己实现的,使用 .split() 已经可以实现的功能,所以我在这里使用了它。

    然后我们有一个pointer,它跟踪我们正在处理的单词,并在每次运行displayNextWord() 时递增。 displayNextWord() 只是检查是否还有要显示的单词:如果是,则打印该单词,然后设置超时以在 1 秒后再次运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      相关资源
      最近更新 更多