我对setTimeout命令有点困惑。下面的代码获取一个文本并返回console.log()字段中的单个单词。当然,这个过程是立即计算出来的。我想设置进程的Timeout,这样代码就会每秒给我一个单词。我在for循环中有点纠结于嵌套的if条件,没有在这个板上找到解决方案,也没有自己编写代码。
如果你能帮我,那就太棒了。非常感谢。:)
Robert
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);
}
- 按间距拆分
.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);
试试这个:
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...
工作示例:JSFiddle。
您发布的大多数示例代码都是您自己使用.split()实现的,所以我在这里使用了它。
然后我们有一个pointer
,它跟踪我们要访问的单词,并在每次运行displayNextWord()
时递增。displayNextWord()
只需检查是否还有一个单词要显示:如果有,它会打印该单词,然后设置超时,在1秒后再次运行。