user3036473
user3036473

Reputation: 1

setTimeout for nested if condition in for loop

I got a bit confused with the setTimeout command. The following code takes a text and gives back the single words in the console.log() field. But of course the process is caluclated immediately. I want to setTimeout the process, so the code will give me for example one word per second. I'm a bit stuggleing with the nested if condition in a for loop and didn't manage to find the solution in on this board or code it myself.

If you can help me, that would be awesome. Thanks a lot. :)

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);
       }

Upvotes: 0

Views: 888

Answers (2)

Shai
Shai

Reputation: 7307

Try this:

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.

Most of the sample code you posted was your own implementation of what can already be achieved using .split(), so I've used that here.

We then have a pointer which keeps track of which word we are up to, and gets incremented on each run of displayNextWord(). displayNextWord() simply checks whether there is still a word to display: if so, it prints that word, then sets a timeout to run again after 1 second.

Upvotes: 1

l2aelba
l2aelba

Reputation: 22177

  • Split by spacing .split(' ');
  • Use setInterval();
  • When done clearInterval();

Result :

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);

Upvotes: 1

Related Questions