Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making text blink a certain number of times?

I'm trying to make this blinking text stop after 3 seconds (or 3-5 blinks). I've set the blink rate to about the right speed, but cannot figure out how to make it stop.

Here's the code:

$('.blink').each(function() {
var elem = $(this);
setInterval(function() {
    if (elem.css('visibility') == 'hidden') {
        elem.css('visibility', 'visible');
    } else {
        elem.css('visibility', 'hidden');
    }    
}, 200);
});

Any suggestions?

I've compiled a jQuery fiddle here: http://jsfiddle.net/M4Fcd/173/

like image 386
WebMW Avatar asked Dec 06 '22 03:12

WebMW


2 Answers

setInterval goes on indefinitely - or until stopped.

What you need to do is capture the intervalID when you create the interval and then clear the interval after you are done with it

var intervalID = setInterval(function....);

// when done
clearInterval(intervalID);

In your particular case:

$('.blink').each(function() {
  var elem = $(this);
  // count the blinks
  var count = 1;
  var intervalId = setInterval(function() {
    if (elem.css('visibility') == 'hidden') {
        elem.css('visibility', 'visible');
        // increment counter when showing to count # of blinks and stop when visible
        if (count++ === 3) {
            clearInterval(intervalId);
        }
    } else {
        elem.css('visibility', 'hidden');
    }    
  }, 200);
});

Updated fiddle http://jsfiddle.net/M4Fcd/186/

like image 99
Matt Pileggi Avatar answered Dec 23 '22 10:12

Matt Pileggi


You could also use fadeIn/fadeOut like this

$('.blink').each(function() {
    var elem = $(this);
    elem.fadeOut(100)
        .fadeIn(100)
        .fadeOut(100)
        .fadeIn(100)
        .fadeOut(100)
        .fadeIn(100);
});

jsFiddle

like image 43
RobinvdA Avatar answered Dec 23 '22 09:12

RobinvdA