Q:

Performing a 'for loop' on an element to blink

I'm currently trying to make an element blink 5 times with a loop so that I can replace current code. And this has to be replaced by a loop for requirements of class. My current code is
    $(function(){

      setTimeout(function() {
      $(".blink").animate({opacity:0},700,"linear",function(){
        $(this).animate({opacity:1},700);
        $(this).animate({opacity:0},700);
        $(this).animate({opacity:1},700);
        $(this).animate({opacity:0},700);
        $(this).animate({opacity:1},700);
        $(this).animate({opacity:0},700);
        $(this).animate({opacity:1},700);
        $(this).animate({opacity:0},700);
        $(this).animate({opacity:1},700);
        });
      }, 1000);
});

My last trial of using a loop on this function was
$(function(){

    for (var i = 0; i < 4; i++) {
      setTimeout(function() {
      $(".blink").animate({opacity:0},700,"linear",function(){
        $(this).animate({opacity:1},700);
        });
      }, 1000);
    }
});

But it's only blinking one time... I have a feeling it's because "i" needs to be some place in the function, but I have yet to have success with any placements. Thanks

A:

You can increment the timeout delay using i as a multiplier
for (var i = 0; i < 4; i++) {
  setTimeout(function() {
      $(".blink").animate({opacity:0},700,"linear",function(){
         $(this).animate({opacity:1},700);
      });
  }, 1500 * i);
}

Or set up a recursive function
function blink(counter){   

      $(".blink").animate({opacity:0},700,"linear",function(){
         $(this).animate({opacity:1},700,function(){
            counter ++;
             if(counter < 5){
              // start over
              blink(counter);
             }  
         });

     });  

}

use
blink(1);

