jquerytimeouteachflashing

jQuery Flash Words


I'm trying to take a sentence and go through flashing the words, and the last word fade out, for a longer period.

For some reason it's only doing the last string in the array.

Thanks for your time : )

jsfiddle

<script>
    $(function() {

    //take sentence
      var lines = [
        'Apples are red',
        'Sky is blue',
        'Grass is green'
      ];
    //set index
    var i = 0;

    showLinesHelper();

    function showLinesHelper()  {
    //take line and split into words
      words = lines[i].split(' ');
      $.each(words, function(k, v)  {
    //take each word and flash
        if(k != words.length)  {
    //if not last word
          setTimeout(function()  {
    //display word into class
            $('.words').html(v);
    //take array index x milliseconds
          }, k * 500);
        }else  {
    //last word
          setTimeout(function()  {
    //display word into class
            $('.words').html(v);
    //take array index x milliseconds
    //show last word for a longer amount of time
          }, k * 1000);
        }
      });
      i++;
      if(i < lines.length)  {

    //if array is less than index, call again
        setTimeout(showLinesHelper(), 0);

      }
    }

    });
</script>

    <div class="words">
    </div>

Solution

  • I did some changes to your code, I created a new variable time to keep a new count for the timeout and added a -1 to the IF condition because the array length start at 0 and the ELSE was never hit it.

    $(function() {
    
    //take sentence
      var lines = [
        'Apples are red',
        'Sky is blue',
        'Grass is green'
      ];
    var i = 0;
    var time = 1;
    showLinesHelper();
    
    function showLinesHelper()  {
    //take line and split into words
      words = lines[i].split(' ');
      $.each(words, function(k, v)  {
    //take each word and flash
    
        if(k != words.length - 1)  {
    //if not last word
    
          setTimeout(function()  {
    //display word into class
            $('.words').html(v);
    //take array index x milliseconds
          }, time * 500);
          time = time + 2;
        }else  {
    //last word
    
          setTimeout(function()  {
         
    //display word into class
            $('.words').html(v);
    //take array index x milliseconds
    //show last word for a longer amount of time
          }, time * 500);
          time = time + 5;
        }
      });
      i++;
      if(i < lines.length)  {
    
    //if array is less than index, call again
        setTimeout(showLinesHelper(), 0);
    
      }
    }
    
    });