Javascript for循环中嵌套if条件的setTimeout
我对setTimeout命令有点困惑。下面的代码获取一个文本并返回console.log()字段中的单个单词。但当然,这个过程是立即计算出来的。我想设置进程超时,因此代码会给我例如每秒一个单词。我对for循环中的嵌套if条件有点不适应,没有在这个板上找到解决方案,也没有自己编写代码 如果你能帮我,那就太棒了。非常感谢。:) 罗伯特Javascript for循环中嵌套if条件的setTimeout,javascript,loops,for-loop,nested,settimeout,Javascript,Loops,For Loop,Nested,Settimeout,我对setTimeout命令有点困惑。下面的代码获取一个文本并返回console.log()字段中的单个单词。但当然,这个过程是立即计算出来的。我想设置进程超时,因此代码会给我例如每秒一个单词。我对for循环中的嵌套if条件有点不适应,没有在这个板上找到解决方案,也没有自己编写代码 如果你能帮我,那就太棒了。非常感谢。:) 罗伯特 text = "test text bla blah blah blah Eric \ blah blah blah Eric blah blah Eric blah
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);
}
text=“测试文本布拉布拉布拉布拉埃里克\
诸如此类诸如此类埃里克诸如此类埃里克诸如此类\
诸如此类诸如此类诸如此类的埃里克”;
var space=“”;
var h=0;
var命中率=[];
变异词;
for(var h=0;h
- 按间距拆分
。拆分(“”)代码>
- 使用
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);
试试这个:
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...
您发布的大多数示例代码都是您自己的实现,它已经可以使用实现,所以我在这里使用了它
然后我们有一个
指针
,它跟踪我们使用的单词,并在每次运行displayneword()
时递增displayNextWord()
只需检查是否还有一个字要显示:如果有,它会打印该字,然后设置一个超时,在1秒后再次运行。如果您知道所有命令,就会发生这种情况。;)谢谢你的代码(和拆分)。